MongoDB query in object of arrays


Let us first create a collection with documents −

> db.demo194.insertOne(
...   {
...      "_id": 101,
...      "details": {
...         "otherDetails": {
...            "List1": ["MongoDB", "MySQL"],
...            "List2": ["Java"],
...            "List3": ["MongoDB", "C"]
...         }
...      }
...   }
...);
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo194.insertOne( {"_id": 102, "details": { "otherDetails": { "List1": ["Java", "C"],        "List2": ["C++"], "List3": ["Python", "Spring"] } } } );
{ "acknowledged" : true, "insertedId" : 102 }

Display all documents from a collection with the help of find() method −

> db.demo194.find();

This will produce the following output −

{ "_id" : 101, "details" : { "otherDetails" : { "List1" : [ "MongoDB", "MySQL" ], "List2" : [ "Java" ], "List3" : [ "MongoDB", "C" ] } } }
{ "_id" : 102, "details" : { "otherDetails" : { "List1" : [ "Java", "C" ], "List2" : [ "C++" ], "List3" : [ "Python", "Spring" ] } } }

Here is the how to query object of arrays −

> db.demo194.find({ "details.otherDetails.List1": "MongoDB" })

This will produce the following output −

{ "_id" : 101, "details" : { "otherDetails" : { "List1" : [ "MongoDB", "MySQL" ], "List2" : [ "Java" ], "List3" : [ "MongoDB", "C" ] } } }

Updated on: 27-Mar-2020

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements