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



To order a list, use sort(). Let us create a collection with documents −

> db.demo581.insertOne({"Name":"Chris","Score":56});{    "acknowledged" : true, "insertedId" : ObjectId("5e91cbbbfd2d90c177b5bcb6") } > db.demo581.insertOne({"Name":"Bob","Score":240});{    "acknowledged" : true, "insertedId" : ObjectId("5e91cbbbfd2d90c177b5bcb7") } > db.demo581.insertOne({"Name":"David","Score":150});{    "acknowledged" : true, "insertedId" : ObjectId("5e91cbbcfd2d90c177b5bcb8") }

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

> db.demo581.find();

This will produce the following output −

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

Following is the query to order a list and add position to its items in MongoDB −

> db.demo581.createIndex({Score:1}) {    "createdCollectionAutomatically" : false,    "numIndexesBefore" : 1,    "numIndexesAfter" : 2,    "ok" : 1 } > var i = 1; > db.demo581.find().sort({"Score": 1}).forEach(function (d){ ...    d.Position = i; ...    i++; ...    db.demo581.save(d); ... })

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

> db.demo581.find();

This will produce the following output −

{ "_id" : ObjectId("5e91cbbbfd2d90c177b5bcb6"), "Name" : "Chris", "Score" : 56, "Position" : 1 } { "_id" : ObjectId("5e91cbbbfd2d90c177b5bcb7"), "Name" : "Bob", "Score" : 240, "Position" : 3 } { "_id" : ObjectId("5e91cbbcfd2d90c177b5bcb8"), "Name" : "David", "Score" : 150, "Position" : 2 }
Updated on: 2020-05-15T06:19:28+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements