- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 ] }
- Related Articles
- MongoDB query to find value in array with multiple criteria (range)
- MongoDB query to find matching documents given an array with values?
- MongoDB query to add multiple documents
- How to match multiple criteria inside an array with MongoDB?
- MongoDB query to pull multiple values from array
- Match multiple criteria inside an array with MongoDB?
- Find value in a MongoDB Array with multiple criteria?
- MongoDB query to match documents that contain an array field
- Query to retrieve multiple items in an array in MongoDB?
- MongoDB query to match documents with array values greater than a specific value
- MongoDB query to find and return subdocument with criteria?
- MongoDB query to get documents with multiple conditions set in $or?
- MongoDB query to get distinct FirstName values from documents
- MongoDB aggregate to convert multiple documents into single document with an array?
- MongoDB query to find multiple matchings inside array of objects?

Advertisements