Finding a specific item in subdocument with MongoDB?

MongoDBDatabaseBig Data Analytics

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" } ] }
raja
Published on 30-Mar-2020 08:23:12
Advertisements