You can use positional operator $ for this. Let us first create a collection with documents −
> db.subElementQueryingDemo.insertOne(
... {
... "ClientName":"Chris",
... "Status": [ { "isMarried": true }, { "isMarried": false } ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccf28c9dceb9a92e6aa1953")
}Following is the query to display all documents from a collection with the help of find() method −
> db.subElementQueryingDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5ccf28c9dceb9a92e6aa1953"),
"ClientName" : "Chris",
"Status" : [
{
"isMarried" : true
},
{
"isMarried" : false
}
]
}Here is how you can query sublement in MongoDB −
> db.subElementQueryingDemo.find({ "Status.isMarried": true }, {ClientName: 1, 'Status.$': 1}).pretty();This will produce the following output −
{
"_id" : ObjectId("5ccf28c9dceb9a92e6aa1953"),
"ClientName" : "Chris",
"Status" : [
{
"isMarried" : true
}
]
}