How to fire find query on sub-documents in MongoDB?

MongoDBDatabaseBig Data Analytics

For sub-documents, use the dot notation. Let us first create a collection with documents −

> db.demo537.insertOne({"details":{"SubjectName":"MongoDB"}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c8a10ef4dcbee04fbbc05")
}
> db.demo537.insertOne({"details":{"SubjectName":"MySQL"}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c8a4bef4dcbee04fbbc06")
}
> db.demo537.insertOne({"details":{"SubjectName":"Java"}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c8a51ef4dcbee04fbbc07")
}

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

> db.demo537.find();

This will produce the following output −

{ "_id" : ObjectId("5e8c8a10ef4dcbee04fbbc05"), "details" : { "SubjectName" : "MongoDB" } }
{ "_id" : ObjectId("5e8c8a4bef4dcbee04fbbc06"), "details" : { "SubjectName" : "MySQL" } }
{ "_id" : ObjectId("5e8c8a51ef4dcbee04fbbc07"), "details" : { "SubjectName" : "Java" } }

Following is the query to fire query on sub-documents in MongoDB −

> db.demo537.count({'details.SubjectName': 'MongoDB'})

This will produce the following output −

1
raja
Published on 14-May-2020 10:09:14
Advertisements