- 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
Searching for ranges in MongoDB?
To search for ranges, use sort() with limit(). Let us create a collection with documents −
> db.demo665.insertOne({"Value":10}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1bf1424113ea5458c7d08") } > db.demo665.insertOne({"Value":15}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1bf1b24113ea5458c7d09") } > db.demo665.insertOne({"Value":55}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1bf1e24113ea5458c7d0a") } > db.demo665.insertOne({"Value":25}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1bf2324113ea5458c7d0b") } > db.demo665.insertOne({"Value":20}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1bf2b24113ea5458c7d0c") }
Display all documents from a collection with the help of find() method −
> db.demo665.find();
This will produce the following output −
{ "_id" : ObjectId("5ea1bf1424113ea5458c7d08"), "Value" : 10 } { "_id" : ObjectId("5ea1bf1b24113ea5458c7d09"), "Value" : 15 } { "_id" : ObjectId("5ea1bf1e24113ea5458c7d0a"), "Value" : 55 } { "_id" : ObjectId("5ea1bf2324113ea5458c7d0b"), "Value" : 25 } { "_id" : ObjectId("5ea1bf2b24113ea5458c7d0c"), "Value" : 20 }
Following is the query to search for ranges in MongoDB −
> db.demo665.find({Value:{$lte:30}}).sort({Value:-1}).limit(2);
This will produce the following output −
{ "_id" : ObjectId("5ea1bf2324113ea5458c7d0b"), "Value" : 25 } { "_id" : ObjectId("5ea1bf2b24113ea5458c7d0c"), "Value" : 20 }
Advertisements