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

MongoDBDatabaseBig Data Analytics

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 } }
raja
Published on 03-Apr-2020 16:55:20
Advertisements