MongoDB query to match documents with array values greater than a specific value

MongoDBDatabaseBig Data Analytics

You can use $elemMatch. The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

Let us create a collection with documents −

> db.demo701.insertOne({"ListOfValues":[100,200,300]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6e8cf551299a9f98c93b0")
}
> db.demo701.insertOne({"ListOfValues":[500,700,1000]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6e8d8551299a9f98c93b1")
}
> db.demo701.insertOne({"ListOfValues":[300,350,450]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6e8e1551299a9f98c93b2")
}

Display all documents from a collection with the help of find() method −

> db.demo701.find();

This will produce the following output −

{ "_id" : ObjectId("5ea6e8cf551299a9f98c93b0"), "ListOfValues" : [ 100, 200, 300 ] }
{ "_id" : ObjectId("5ea6e8d8551299a9f98c93b1"), "ListOfValues" : [ 500, 700, 1000 ] }
{ "_id" : ObjectId("5ea6e8e1551299a9f98c93b2"), "ListOfValues" : [ 300, 350, 450 ] }

Following is the query to match documents with array values greater than a specific value −

> db.demo701.find({"ListOfValues":{$elemMatch:{$gt:500}}});

This will produce the following output −

{ "_id" : ObjectId("5ea6e8d8551299a9f98c93b1"), "ListOfValues" : [ 500, 700, 1000 ] }
raja
Published on 14-May-2020 13:05:51
Advertisements