Match MongoDB documents with field value greater than a specific number and fetch them?

MongoDBDatabaseBig Data Analytics

To match, use $match in MongoDB. For values greater than a specific number, use $gt. Let us create a collection with documents −

> db.demo730.insertOne({"Name" : "Chris", "Marks" : 33 });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eac54cd56e85a39df5f6339")
}
> db.demo730.insertOne({ "Name" : "David", "Marks" : 89});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eac54cd56e85a39df5f633a")
}
> db.demo730.insertOne({ "Name" : "Chris", "Marks" : 45 });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eac54ce56e85a39df5f633b")
}

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

> db.demo730.find();

This will produce the following output −

{ "_id" : ObjectId("5eac54cd56e85a39df5f6339"), "Name" : "Chris", "Marks" : 33 }
{ "_id" : ObjectId("5eac54cd56e85a39df5f633a"), "Name" : "David", "Marks" : 89 }
{ "_id" : ObjectId("5eac54ce56e85a39df5f633b"), "Name" : "Chris", "Marks" : 45 }

Following is the query to match MongoDB documents with field value greater than a specific number and fetch them −

> db.demo730.aggregate([
...    { $sort: { _id: -1 } },
...    { $limit: 3 },
...    {$match: { $or: [ {"Name": "Chris", "Marks": { "$gt": 40 }}, {"Name": "David"} ]}}
... ])

This will produce the following output −

{ "_id" : ObjectId("5eac54ce56e85a39df5f633b"), "Name" : "Chris", "Marks" : 45 }
{ "_id" : ObjectId("5eac54cd56e85a39df5f633a"), "Name" : "David", "Marks" : 89 }
raja
Published on 15-May-2020 12:49:47
Advertisements