Searching for ranges in MongoDB?

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 13-May-2020 09:41:24
Advertisements