- 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
MongoDB query to fetch elements between a range excluding both the numbers used to set range?
Let’s say both the numbers are 50 and 60. You can use below syntax −
db.yourCollectionName.find({yourFieldName: { $gt : 50 , $lt : 60 } } );
If you want to include 50 and 60 also then use below syntax −
db.yourCollectionName.find({yourFieldName: { $gte : 50 , $lte : 60 } } );
Let us first create a collection with documents −
> db.returnEverythingBetween50And60.insertOne({"Amount":55}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c42eedc6604c74817cdb") } > db.returnEverythingBetween50And60.insertOne({"Amount":45}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c432edc6604c74817cdc") } > db.returnEverythingBetween50And60.insertOne({"Amount":50}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c436edc6604c74817cdd") } > db.returnEverythingBetween50And60.insertOne({"Amount":59}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c43aedc6604c74817cde") } > db.returnEverythingBetween50And60.insertOne({"Amount":60}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c43eedc6604c74817cdf") } > db.returnEverythingBetween50And60.insertOne({"Amount":49}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c442edc6604c74817ce0") } > db.returnEverythingBetween50And60.insertOne({"Amount":71}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3c445edc6604c74817ce1") }
Following is the query to display all documents from a collection with the help of find() method −
> db.returnEverythingBetween50And60.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd3c42eedc6604c74817cdb"), "Amount" : 55 } { "_id" : ObjectId("5cd3c432edc6604c74817cdc"), "Amount" : 45 } { "_id" : ObjectId("5cd3c436edc6604c74817cdd"), "Amount" : 50 } { "_id" : ObjectId("5cd3c43aedc6604c74817cde"), "Amount" : 59 } { "_id" : ObjectId("5cd3c43eedc6604c74817cdf"), "Amount" : 60 } { "_id" : ObjectId("5cd3c442edc6604c74817ce0"), "Amount" : 49 } { "_id" : ObjectId("5cd3c445edc6604c74817ce1"), "Amount" : 71 }
Following is the query to return everything between 50 and 60 excluding both these numbers −
> db.returnEverythingBetween50And60.find({Amount: { $gt : 50 , $lt : 60 } } );
This will produce the following output −
{ "_id" : ObjectId("5cd3c42eedc6604c74817cdb"), "Amount" : 55 } { "_id" : ObjectId("5cd3c43aedc6604c74817cde"), "Amount" : 59 }
Advertisements