Query nested array by more than one condition in MongoDB



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"          ]       }    ] }
Updated on: 2020-03-27T10:33:30+05:30

738 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements