MongoDB query to fetch elements between a range excluding both the numbers used to set range?

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 23-May-2019 08:08:13
Advertisements