Find current and previous documents in MongoDB

MongoDBDatabaseBig Data Analytics

To get the current and previous documents, use sort(). Since we need only 2 documents, therefore, use LIMIT(2).

Let us create a collection with documents −

> db.demo360.insertOne({id:101,"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a10c54a481fef8ec7a15")
}
> db.demo360.insertOne({id:102,"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a11254a481fef8ec7a16")
}
> db.demo360.insertOne({id:103,"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a11a54a481fef8ec7a17")
}
> db.demo360.insertOne({id:104,"Name":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a11f54a481fef8ec7a18")
}

Display all documents from a collection with the help of find() method −

> db.demo360.find();

This will produce the following output −

{ "_id" : ObjectId("5e56a10c54a481fef8ec7a15"), "id" : 101, "Name" : "Chris" }
{ "_id" : ObjectId("5e56a11254a481fef8ec7a16"), "id" : 102, "Name" : "David" }
{ "_id" : ObjectId("5e56a11a54a481fef8ec7a17"), "id" : 103, "Name" : "Bob" }
{ "_id" : ObjectId("5e56a11f54a481fef8ec7a18"), "id" : 104, "Name" : "Mike" }

Following is the query to find current and previous documents in MongoDB −

> db.demo360.find({ id: { $lte: 102 } }, {id:1, Name: 1 }).sort({_id: -1}).limit(2);

This will produce the following output −

{ "_id" : ObjectId("5e56a11254a481fef8ec7a16"), "id" : 102, "Name" : "David" }
{ "_id" : ObjectId("5e56a10c54a481fef8ec7a15"), "id" : 101, "Name" : "Chris" }
raja
Published on 02-Apr-2020 11:51:43
Advertisements