To find by _id on an array of objects, use aggregation and avoid using find(). Let us first create a collection with documents −
> db.demo414.insertOne( ... { ... "_id": "110", ... "details":[ ... { ... "StudentName":"John", ... "StudentMarks":56 ... }, ... { ... "StudentName":"Robert", ... "StudentMarks":98 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : "110" }
Display all documents from a collection with the help of find() method −
> db.demo414.find();
This will produce the following output −
{ "_id" : "110", "details" : [ { "StudentName" : "John", "StudentMarks" : 56 }, { "StudentName" : "Robert", "StudentMarks" : 98 } ] }
Following is the query to find by _id on an array of objects −
> db.demo414.aggregate([{$unwind: "$details"}, {$match:{"details.StudentMarks" :56}}] )
This will produce the following output −
{ "_id" : "110", "details" : { "StudentName" : "John", "StudentMarks" : 56 } }