How to return the position of a document relative to the collection in MongoDB?

To return the position of a document relative to the collection in MongoDB, use sort() along with count() to count how many documents come before the target document in sorted order.

Syntax

db.collection.find({field: {$lt: "targetValue"}}).sort({field: 1}).count();

Sample Data

db.demo47.insertMany([
    {"ClientName": "Adam"},
    {"ClientName": "John"},
    {"ClientName": "Chris"},
    {"ClientName": "Sam"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e267240cfb11e5c34d898f0"),
        ObjectId("5e267243cfb11e5c34d898f1"),
        ObjectId("5e267247cfb11e5c34d898f2"),
        ObjectId("5e26724ccfb11e5c34d898f3")
    ]
}

View Collection Data

db.demo47.find();
{ "_id": ObjectId("5e267240cfb11e5c34d898f0"), "ClientName": "Adam" }
{ "_id": ObjectId("5e267243cfb11e5c34d898f1"), "ClientName": "John" }
{ "_id": ObjectId("5e267247cfb11e5c34d898f2"), "ClientName": "Chris" }
{ "_id": ObjectId("5e26724ccfb11e5c34d898f3"), "ClientName": "Sam" }

Example: Find Position of "John"

To find the position of "John" in alphabetically sorted order ?

db.demo47.find({ClientName: {$lt: "John"}}).sort({ClientName: 1}).count();
2

How It Works

The query counts documents with ClientName values that come before "John" alphabetically. In sorted order: Adam (0), Chris (1), John (2), Sam (3). Two documents come before "John", so its position is 2 (zero-indexed).

Conclusion

Use $lt with count() to find a document's zero-indexed position in a sorted collection. This method counts all documents that would appear before the target document when sorted.

Updated on: 2026-03-15T02:49:15+05:30

624 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements