- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to find documents having two values in an array conforming to multiple criteria?
For this, use $elemMatch operator. Let us first create a collection with documents −
> db.findDocumentsHaving2Demo.insertOne( {_id : 101, Values: [78,98]} ); { "acknowledged" : true, "insertedId" : 101 } > db.findDocumentsHaving2Demo.insertOne( {_id :102, Values : [89,102]} ); { "acknowledged" : true, "insertedId" : 102 }
Following is the query to display all documents from a collection with the help of find() method −
> db.findDocumentsHaving2Demo.find().pretty();
This will produce the following output −
{ "_id" : 101, "Values" : [ 78, 98 ] } { "_id" : 102, "Values" : [ 89, 102 ] }
Following is the query to find documents having two values in Array conforming to multiple criteria −
> db.findDocumentsHaving2Demo.find({$and: [ {Values: {$elemMatch: {$gte: 77, $lte: 78}}}, {Values: {$elemMatch: {$gte:90 , $lte: 110}}}, {'Values.2': {$exists: false}} ]});
This will produce the following output −
{ "_id" : 101, "Values" : [ 78, 98 ] }
Advertisements