For this, use $let along with $expr. Here, $let is used to define temporary variable. The $expr is used for aggregation expressions. Let us create a collection with documents −
> db.demo72.insertOne( ... { ... StudentDetails:[ ... { ... Name: "Chris", ... Age: 21 ... }, ... { ... Name: "David", ... Age: 23 ... }, ... { ... Name: "Bob", ... Age: 20 ... }, ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e29b4ad71bf0181ecc42269") }
Display all documents from a collection with the help of find() method −
> db.demo72.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e29b4ad71bf0181ecc42269"), "StudentDetails" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Bob", "Age" : 20 } ] }
Following is the query on nth element (variable index) of subdocument array −
> db.demo72.find({ ... $expr: { ... $let: { ... vars: { fst: { $arrayElemAt: [ "$StudentDetails", 1 ] } }, ... in: { $eq: [ "$$fst.Name", "David" ] } ... } ... } ... })
This will produce the following output −
{ "_id" : ObjectId("5e29b4ad71bf0181ecc42269"), "StudentDetails" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Bob", "Age" : 20 } ] }