To query nested array, use $elemMatch in MongoDB. Let us create a collection with documents −
> db.demo203.insertOne({ ... "_id" : "101", ... "Name" : "Chris", ... "details1" : [ ... { ... "empName" : "David", ... "salary" : "50000", ... "technology" : [ ... "MySQL", ... "MongoDB" ... ] ... }, ... { ... "empName" : "Carol", ... "salary" : "70000", ... ... "technology" : [ ... "Java", ... "Spring" ... ] ... } ... ] ...} ...); { "acknowledged" : true, "insertedId" : "101" }
Display all documents from a collection with the help of find() method −
> db.demo203.find();
This will produce the following output −
{ "_id" : "101", "Name" : "Chris", "details1" : [ { "empName" : "David", "salary" : "50000", "technology" : [ "MySQL", "MongoDB" ] }, { "empName" : "Carol", "salary" : "70000", "technology" : [ "Java", "Spring" ] } ] }
Here is how to query nested array by more than one condition −
> db.demo203.find( ... {details1: { $elemMatch:{"technology" : "MySQL", "empName":"David"}}} ... ).pretty()
This will produce the following output −
{ "_id" : "101", "Name" : "Chris", "details1" : [ { "empName" : "David", "salary" : "50000", "technology" : [ "MySQL", "MongoDB" ] }, { "empName" : "Carol", "salary" : "70000", "technology" : [ "Java", "Spring" ] } ] }