How to get values greater than a specific value from an embedded list in MongoDB?

MongoDBDatabaseBig Data Analytics

To get values greater than a specific value, use $gt along with find(). Let us create a collection with documents −

> db.demo317.insertOne(
...    {'id':101,
...       'details':[{'Score':78,Name:"Chris"},
...          {'Score':88,Name:"David"}
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50e69cf8647eb59e562060")
}
> db.demo317.insertOne(
...    {'id':102,
...    'details':[{'Score':90,Name:"Chris"},
...       {'Score':91,Name:"David"}
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50e6adf8647eb59e562061")
}

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

> db.demo317.find();

This will produce the following output −

{ "_id" : ObjectId("5e50e69cf8647eb59e562060"), "id" : 101, "details" : [ { "Score" : 78, "Name" : "Chris" }, { "Score" : 88, "Name" : "David" } ] }
{ "_id" : ObjectId("5e50e6adf8647eb59e562061"), "id" : 102, "details" : [ { "Score" : 90, "Name" : "Chris" }, { "Score" : 91, "Name" : "David" } ] }

Following is the query to use $gt on the embedded list in MongoDB to get score records greater than 89 −

> db.demo317.find({"details.Score" :{"$gt": 89}});

This will produce the following output −

{ "_id" : ObjectId("5e50e6adf8647eb59e562061"), "id" : 102, "details" : [ { "Score" : 90, "Name" : "Chris" }, { "Score" : 91, "Name" : "David" } ] }
raja
Published on 02-Apr-2020 06:03:25
Advertisements