How would I filter out sub documents in MongoDB?


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 } }

Updated on: 13-May-2020

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements