Jul 7, 2016

$anyElementTrue operator in MongoDB

Its returns true or false $anyElementTrue accepts only one argument expression and returns true if evaluate expression true otherwise false.
Syntax:


{ $anyElementTrue: [ <expression> ] }


Example: Consider an survey collection with the following documents:


{ "_id" : 1, "responses" : [ true ] }
{ "_id" : 2, "responses" : [ true, false ] }
{ "_id" : 3, "responses" : [ ] }
{ "_id" : 4, "responses" : [ 1, true, "seven" ] }
{ "_id" : 5, "responses" : [ 0 ] }
{ "_id" : 6, "responses" : [ [ ] ] }
{ "_id" : 7, "responses" : [ [ 0 ] ] }
{ "_id" : 8, "responses" : [ [ false ] ] }
{ "_id" : 9, "responses" : [ null ] }
{ "_id" : 10, "responses" : [ undefined ] }


Run Following Query


 db.survey.aggregate(
   [
     { $project: { responses: 1, isAnyTrue: { $anyElementTrue: [ "$responses" ] }, _id: 0 } }
   ]
)



Result:


{ "responses" : [ true ], "isAnyTrue" : true }
{ "responses" : [ true, false ], "isAnyTrue" : true }
{ "responses" : [ ], "isAnyTrue" : false }
{ "responses" : [ 1, true, "seven" ], "isAnyTrue" : true }
{ "responses" : [ 0 ], "isAnyTrue" : false }
{ "responses" : [ [ ] ], "isAnyTrue" : true }
{ "responses" : [ [ 0 ] ], "isAnyTrue" : true }
{ "responses" : [ [ false ] ], "isAnyTrue" : true }
{ "responses" : [ null ], "isAnyTrue" : false }
{ "responses" : [ null ], "isAnyTrue" : false }