How we can perform sort on ObjectId column in MongoDB?


To perform sort on ObjectId column, use sort(). Let us create a collection with document.

> db.demo403.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e6f89b0fac4d418a017858e")
}
> db.demo403.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e6f89b2fac4d418a017858f")
}
> db.demo403.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e6f89b5fac4d418a0178590")
}
> db.demo403.insertOne({"Name":"Adam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e6f89b8fac4d418a0178591")
}

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

> db.demo403.find();

This will produce the following output −

{ "_id" : ObjectId("5e6f89b0fac4d418a017858e"), "Name" : "Chris" }
{ "_id" : ObjectId("5e6f89b2fac4d418a017858f"), "Name" : "David" }
{ "_id" : ObjectId("5e6f89b5fac4d418a0178590"), "Name" : "Bob" }
{ "_id" : ObjectId("5e6f89b8fac4d418a0178591"), "Name" : "Adam" }

Following is the query to perform sort on ObjectId column in MongoDB −

> db.demo403.find().sort({_id:-1});

This will produce the following output −

{ "_id" : ObjectId("5e6f89b8fac4d418a0178591"), "Name" : "Adam" }
{ "_id" : ObjectId("5e6f89b5fac4d418a0178590"), "Name" : "Bob" }
{ "_id" : ObjectId("5e6f89b2fac4d418a017858f"), "Name" : "David" }
{ "_id" : ObjectId("5e6f89b0fac4d418a017858e"), "Name" : "Chris" }

Updated on: 03-Apr-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements