Let us create a collection with documents −
> db.demo313.insertOne({"_id":100,"details":[{"Name":"Chris","Age":24}]}); { "acknowledged" : true, "insertedId" : 100 } > db.demo313.insertOne({"_id":101,"details":[{"Name":"David","Age":22}]}); { "acknowledged" : true, "insertedId" : 101 } > db.demo313.insertOne({"_id":102,"details":[{"Name":"Mike","Age":25}]}); { "acknowledged" : true, "insertedId" : 102 }
Display all documents from a collection with the help of find() method −
> db.demo313.find();
This will produce the following output −
{ "_id" : 100, "details" : [ { "Name" : "Chris", "Age" : 24 } ] } { "_id" : 101, "details" : [ { "Name" : "David", "Age" : 22 } ] } { "_id" : 102, "details" : [ { "Name" : "Mike", "Age" : 25 } ] }
Following is the query to match document with $elemMatch in MongoDB −
db.demo313.find({_id:101},{details: { $elemMatch: { Age: 22 } } } );
This will produce the following output −
{ "_id" : 101, "details" : [ { "Name" : "David", "Age" : 22 } ] }