MongoDB filter multiple sub-documents?



To filter multiple sub-documents in MongoDB, use aggregate(). Let us create a collection with documents −

> db.demo200.insertOne( ...   { ...      "Id":"101", ...      "details1":[ ...         { ...            "isActive":true, ...            "SubjectName":"MySQL" ...         },{ ...            "isActive":false, ...            "SubjectName":"Java" ...         } ...      ], ...      "details2":[ ...         { ...            "isActive":false, ...            "Name":"David" ...         },{ ...            "isActive":true, ...            "Name":"Mike" ...         } ...      ] ...   } ...); {    "acknowledged" : true,    "insertedId" : ObjectId("5e3c374f03d395bdc21346e4") }

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

> db.demo200.find();

This will produce the following output −

{    "_id" : ObjectId("5e3c374f03d395bdc21346e4"), "Id" : "101", "details1" : [       { "isActive" : true, "SubjectName" : "MySQL" },       { "isActive" : false, "SubjectName" : "Java" } ], "details2" : [ { "isActive" : false, "Name" : "David" },       { "isActive" : true, "Name" : "Mike" }    ] }

Following is the query to filter multiple sub-documents −

> var out= [ ...   { ...      "$match": { ...         "Id": "101", ...         "details1.isActive": true, ...         "details2.isActive": true ...      } ...   }, ...   { "$unwind": "$details1" }, ...   { "$unwind": "$details2" }, ...   { ...      "$match": { ...         "details1.isActive": true, ...         "details2.isActive": true ...      } ...   }, ...   { ...      "$group": { ...         "_id": { ...            "_id": "$_id", ...            "Id": "$Id" ...         }, ...         "details2": { "$addToSet" : "$details2" }, ...         "details1": { "$addToSet" : "$details1" } ...      } ...   }, ...   { ...      "$project": { ...         "_id": 0, ...         "Id": "$_id.Id", ...         "details2": 1, ...         "details1": 1 ...      } ...   } ...] > > db.demo200.aggregate(out)

This will produce the following output −

{ "details2" : [ { "isActive" : true, "Name" : "Mike" } ], "details1" : [ { "isActive" : true, "SubjectName" : "MySQL" } ], "Id" : "101" }
Updated on: 2020-03-27T10:19:11+05:30

461 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements