How would I filter out sub documents in MongoDB?

MongoDBDatabaseBig Data Analytics

To filter out sub documents, use MongoDB aggregate and in that, use $unwind. Let us create a collection with documents −

> db.demo662.insertOne(
... {
...    "details":[
...   {
...       Name:"Chris",
...       Marks:35
...    },
...    {
...       Name:"Bob",
...       Marks:45
...    },
...    {
...       Name:"David",
...       Marks:30
...    }
... ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea1b2be24113ea5458c7d04")
}

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

> db.demo662.find();

This will produce the following output −

{ "_id" : ObjectId("5ea1b2be24113ea5458c7d04"), "details" : [ { "Name" : "Chris", "Marks" : 35 }, { "Name" : "Bob", "Marks" : 45 }, { "Name" : "David", "Marks" : 30 } ] }

Following is the query to filter out sub documents −

> db.demo662.aggregate({$unwind:"$details"},{$match:{"details.Marks":{$gt:40}}})

This will produce the following output −

{ "_id" : ObjectId("5ea1b2be24113ea5458c7d04"), "details" : { "Name" : "Bob", "Marks" : 45 } }
raja
Published on 13-May-2020 13:01:45
Advertisements