Query Array for 'true' value at index n in MongoDB?


You can use dot(.) notation for this. Let us first create a collection with documents −

>db.containsTrueValueDemo.insertOne({"IsMarried":[true,false,true,true,true,true,false,true,false,false,true]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd5039c2cba06f46efe9ef5")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.containsTrueValueDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd5039c2cba06f46efe9ef5"),
   "IsMarried" : [
      true,
      false,
      true,
      true,
      true,
      true,
      false,
      true,
      false,
      false,
      true
   ]
}

Query Array for 'true' value at index n -

> db.containsTrueValueDemo.find({'IsMarried.2' : true});

This will produce the following output −

{ "_id" : ObjectId("5cd5039c2cba06f46efe9ef5"), "IsMarried" : [ true, false, true, true, true, true, false, true, false, false, true ] }

Query to Array for 'true' value at index n −

> db.containsTrueValueDemo.find({$and :  [ {'IsMarried.0' : true}, {'IsMarried.2' : true} ] } );

This will produce the following output −

{ "_id" : ObjectId("5cd5039c2cba06f46efe9ef5"), "IsMarried" : [ true, false, true, true, true, true, false, true, false, false, true ] }

Updated on: 30-Jul-2019

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements