Find by _id on an array of objects in MongoDB database?


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

Updated on: 03-Apr-2020

639 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements