Syntax error MongoDB query to find documents having two values in an array conforming to multiple criteria?

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 ] }
Updated on: 2019-07-30T22:30:26+05:30

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements