इसके लिए aggregate() का उपयोग करें। मान लें हमें field "Age" value "21" वाले documents fetch करने हैं।
Collection बनाना
> db.demo685.insertOne(
... {
... "details":
... [
... { Name:"Chris", Age:21 },
... { Name:"David", Age:23 },
... { Name:"Bob", Age:21 }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : ObjectId("5ea54f6fa7e81adc6a0b395b") }
सभी Documents Display करना
> db.demo685.find();
Output:
{ "_id" : ObjectId("5ea54f6fa7e81adc6a0b395b"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Bob", "Age" : 21 } ] }
MongoDB Aggregation Query
> db.demo685.aggregate([ { $unwind: "$details" }, { $match: { "details.Age": 21 } }, { $project: {_id: 0}} ]).pretty();
Output:
{ "details" : { "Name" : "Chris", "Age" : 21 } }
{ "details" : { "Name" : "Bob", "Age" : 21 } }
व्याख्या: $unwind ने details array flatten किया। $match ने details.Age: 21 वाले documents filter किए। $project में _id: 0 से _id exclude किया गया। Output में केवल matching array elements दिखे।