How do I order a list and add position to its items in MongoDB?

To order a list and add position to its items in MongoDB, use sort() combined with forEach() to iterate through the sorted results and assign position values. This approach permanently adds position data to your documents based on the specified sort order.

Syntax

var i = 1;
db.collection.find().sort({fieldName: 1}).forEach(function(doc) {
    doc.Position = i;
    i++;
    db.collection.save(doc);
});

Sample Data

db.demo581.insertMany([
    {"Name": "Chris", "Score": 56},
    {"Name": "Bob", "Score": 240},
    {"Name": "David", "Score": 150}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e91cbbbfd2d90c177b5bcb6"),
        ObjectId("5e91cbbbfd2d90c177b5bcb7"),
        ObjectId("5e91cbbcfd2d90c177b5bcb8")
    ]
}

Display all documents from the collection ?

db.demo581.find();
{ "_id": ObjectId("5e91cbbbfd2d90c177b5bcb6"), "Name": "Chris", "Score": 56 }
{ "_id": ObjectId("5e91cbbbfd2d90c177b5bcb7"), "Name": "Bob", "Score": 240 }
{ "_id": ObjectId("5e91cbbcfd2d90c177b5bcb8"), "Name": "David", "Score": 150 }

Add Position Based on Score Order

Create an index for better sorting performance and add position values ?

db.demo581.createIndex({Score: 1});
{
    "createdCollectionAutomatically": false,
    "numIndexesBefore": 1,
    "numIndexesAfter": 2,
    "ok": 1
}

Sort by Score in ascending order and assign position values ?

var i = 1;
db.demo581.find().sort({"Score": 1}).forEach(function(d) {
    d.Position = i;
    i++;
    db.demo581.save(d);
});

Verify Results

db.demo581.find().sort({"Position": 1});
{ "_id": ObjectId("5e91cbbbfd2d90c177b5bcb6"), "Name": "Chris", "Score": 56, "Position": 1 }
{ "_id": ObjectId("5e91cbbcfd2d90c177b5bcb8"), "Name": "David", "Score": 150, "Position": 2 }
{ "_id": ObjectId("5e91cbbbfd2d90c177b5bcb7"), "Name": "Bob", "Score": 240, "Position": 3 }

Key Points

  • The sort() method orders documents by the specified field (1 = ascending, -1 = descending).
  • forEach() iterates through each sorted document to assign position values.
  • Creating an index on the sort field improves query performance.
  • The save() method updates each document with the new Position field.

Conclusion

Combine sort() and forEach() to order documents and permanently add position values. This method ensures each document receives a position number based on the specified sort criteria.

Updated on: 2026-03-15T03:44:36+05:30

344 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements