
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Match Multiple Criteria Inside an Array with MongoDB
For this, use aggregate framework with the $elemMatch operator. Let us first create a collection with documents −
> db.matchMultipleCriteriaDemo.insertOne({ "EmployeeDetails": [ {"EmployeeName": "Chris", "Salary": 45000, "Language":"Java"}, {"EmployeeName": "Robert", "Salary": 41000, "Language":"Python"} ] }); { "acknowledged" : true, "insertedId" : ObjectId("5cea3bf0ef71edecf6a1f689") } > db.matchMultipleCriteriaDemo.insertOne({ "EmployeeDetails": [ {"EmployeeName": "David", "Salary": 55000, "Language":"C++"}, {"EmployeeName": "Bob", "Salary": 61000, "Language":"C"} ] }); { "acknowledged" : true, "insertedId" : ObjectId("5cea3bf1ef71edecf6a1f68a") }
Following is the query to display all documents from a collection with the help of find() method −
> db.matchMultipleCriteriaDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cea3bf0ef71edecf6a1f689"), "EmployeeDetails" : [ { "EmployeeName" : "Chris", "Salary" : 45000, "Language" : "Java" }, { "EmployeeName" : "Robert", "Salary" : 41000, "Language" : "Python" } ] } { "_id" : ObjectId("5cea3bf1ef71edecf6a1f68a"), "EmployeeDetails" : [ { "EmployeeName" : "David", "Salary" : 55000, "Language" : "C++" }, { "EmployeeName" : "Bob", "Salary" : 61000, "Language" : "C" } ] }
Following is the query to match multiple criteria inside an array −
> db.matchMultipleCriteriaDemo.aggregate({ "$match": { "EmployeeDetails": { "$elemMatch": { "EmployeeName": "Bob", "Language":"C" } } }} ).pretty();
This will produce the following output −
{ "_id" : ObjectId("5cea3bf1ef71edecf6a1f68a"), "EmployeeDetails" : [ { "EmployeeName" : "David", "Salary" : 55000, "Language" : "C++" }, { "EmployeeName" : "Bob", "Salary" : 61000, "Language" : "C" } ] }
Advertisements