Finding a specific item in subdocument with MongoDB?


To get a specific item in a sudocument, use the dot(.) notation. Let us create a collection with documents −

> db.demo81.insertOne({"StudentDetails":[{"StudentName":"Carol","StudentSubject":"Java"},{ "StudentName" : "David", "StudentSubject" : "MongoDB" }]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bf6ec71bf0181ecc4229d")
}
> db.demo81.insertOne({"StudentDetails":[{"StudentName":"Mike","StudentSubject":"Python"},{ "StudentName" : "David", "StudentSubject" : "C" }]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bf70471bf0181ecc4229e")
}
> db.demo81.insertOne({"StudentDetails":[{"StudentName":"Jace","StudentSubject":"C++"},{    "StudentName" : "John", "StudentSubject" : "MySQL" }]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bf72071bf0181ecc4229f")
}

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

> db.demo81.find();

This will produce the following output −

{
   "_id" : ObjectId("5e2bf6ec71bf0181ecc4229d"), "StudentDetails" : [
      { "StudentName" : "Carol", "StudentSubject" : "Java" },
      {"StudentName" : "David", "StudentSubject" : "MongoDB" }
   ]
}
{
   "_id" : ObjectId("5e2bf70471bf0181ecc4229e"), "StudentDetails" : [
      { "StudentName" : "Mike", "StudentSubject" : "Python" },
      { "StudentName" : "David", "StudentSubject" : "C" }
   ]
}
{
   "_id" : ObjectId("5e2bf72071bf0181ecc4229f"), "StudentDetails" : [
      { "StudentName" : "Jace", "StudentSubject" : "C++" },
      { "StudentName" : "John", "StudentSubject" : "MySQL" }
   ] 
}

Following is the query to find item in a subdocument with MongoDB −

> db.demo81.find({"StudentDetails.StudentSubject":"MongoDB"});

This will produce the following output −

{ "_id" : ObjectId("5e2bf6ec71bf0181ecc4229d"), "StudentDetails" : [ { "StudentName" : "Carol", "StudentSubject" : "Java" }, { "StudentName" : "David", "StudentSubject" : "MongoDB" } ] }

Updated on: 30-Mar-2020

96 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements