Query array of subdocuments in MongoDB

MongoDBDatabaseBig Data Analytics

To query an array of subdocuments, use $unwind in MongoDB. Let us create a collection with documents −

> db.demo499.insertOne({
... "details":
...    [
...       {
...          Name :"MIT",
...          Rank: 1,
...          "CountryName":"US"
...       },
...
...       {
...          Name :"Stanford University",
...          Rank: 2
...       },
...
...       {
...          Name :"University of California, Berkeley",
...          Rank: 3
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e87433d987b6e0e9d18f558")
}

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

> db.demo499.find();

This will produce the following output −

{ "_id" : ObjectId("5e87433d987b6e0e9d18f558"), "details" : [ { "Name" : "MIT", "Rank" : 1,
"CountryName" : "US" }, { "Name" : "Stanford University", "Rank" : 2 }, { "Name" : "University
of California, Berkeley", "Rank" : 3 } ] }

Following is how to query an array of subdocuments −

> db.demo499.aggregate({$unwind: "$details"},
... {$match: {"details.CountryName":{$exists: true}}},
... {$project: {"details.Name": 1, "details.CountryName": 1, "_id": 0}})

This will produce the following output −

{ "details" : { "Name" : "MIT", "CountryName" : "US" } }
raja
Published on 13-May-2020 05:51:10
Advertisements