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

MongoDBDatabaseBig Data Analytics

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 ] }
raja
Published on 23-May-2019 12:41:12
Advertisements