How to find a certain element in the MongoDB embedded document?



To find a certain element, use $project in MongoDB. Let us create a collection with documents −

> db.demo744.insertOne( ...    { ...       studentInformation: ...       [ ...          { ...             studentName:"Robert", ...             grade:"A" ...          }, ...          { ...             studentName:"Bob", ...             grade:"C" ...          }, ...          { ...             studentName:"John", ...             grade:"B" ...          }, ...          { ...             studentName:"Sam", ...             grade:"A" ...          } ...       ] ...    } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5ead928a57bb72a10bcf0684") }

Display all documents from a collection with the help of find() method −

> db.demo744.find();

This will produce the following output −

{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : [ { "studentName" : "Robert", "grade" : "A" }, { "studentName" : "Bob", "grade" : "C" }, { "studentName" : "John", "grade" : "B" }, { "studentName" : "Sam", "grade" : "A" } ] }

Following is the query to find a certain element in the embedded document −

> db.demo744.aggregate( ...    { $unwind: '$studentInformation' }, ...    { $match: {'studentInformation.grade':"A"}}, ...    { $project: {"studentInformation.studentName": 1}} ... )

This will produce the following output −

{ "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : { "studentName" : "Robert" } } { "_id" : ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation" : { "studentName" : "Sam" } }
Updated on: 2020-06-30T08:02:54+05:30

194 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements