Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find current and previous documents in MongoDB
To get the current and previous documents in MongoDB, use sort() with limit() to retrieve the most recent documents based on a specific criteria. This approach helps you find the latest two records that match your query conditions.
Syntax
db.collection.find(
{ field: { $lte: value } },
{ projection }
).sort({ _id: -1 }).limit(2);
Sample Data
Let us create a collection with sample documents:
db.demo360.insertMany([
{ id: 101, "Name": "Chris" },
{ id: 102, "Name": "David" },
{ id: 103, "Name": "Bob" },
{ id: 104, "Name": "Mike" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e56a10c54a481fef8ec7a15"),
ObjectId("5e56a11254a481fef8ec7a16"),
ObjectId("5e56a11a54a481fef8ec7a17"),
ObjectId("5e56a11f54a481fef8ec7a18")
]
}
Display all documents from the collection:
db.demo360.find();
{ "_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" }
Example: Find Current and Previous Documents
To find the current and previous documents where id is less than or equal to 102:
db.demo360.find(
{ id: { $lte: 102 } },
{ id: 1, Name: 1 }
).sort({ _id: -1 }).limit(2);
{ "_id": ObjectId("5e56a11254a481fef8ec7a16"), "id": 102, "Name": "David" }
{ "_id": ObjectId("5e56a10c54a481fef8ec7a15"), "id": 101, "Name": "Chris" }
How It Works
-
{ id: { $lte: 102 } }filters documents with id ? 102 -
sort({ _id: -1 })sorts by ObjectId in descending order (newest first) -
limit(2)returns only the top 2 matching documents -
Projection
{ id: 1, Name: 1 }includes only specified fields
Conclusion
Use find() with filtering conditions, sort() in descending order, and limit(2) to retrieve current and previous documents efficiently. This pattern works well for finding the most recent records based on any criteria.
Advertisements
