![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Match MongoDB documents with field value greater than a specific number and fetch them?
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 }
Advertisements