Sorting field value (FirstName) for MongoDB?


To sort values, use sort() in MongoDB. Let us first create a collection with documents −

> db.demo365.insertOne({"FirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57d5b6d0ada61456dc936f")
}
> db.demo365.insertOne({"FirstName":"Adam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57d5bad0ada61456dc9370")
}
> db.demo365.insertOne({"FirstName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57d5bed0ada61456dc9371")
}
> db.demo365.insertOne({"FirstName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57d5c0d0ada61456dc9372")
}

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

> db.demo365.find();

This will produce the following output −

{ "_id" : ObjectId("5e57d5b6d0ada61456dc936f"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5e57d5bad0ada61456dc9370"), "FirstName" : "Adam" }
{ "_id" : ObjectId("5e57d5bed0ada61456dc9371"), "FirstName" : "John" }
{ "_id" : ObjectId("5e57d5c0d0ada61456dc9372"), "FirstName" : "Bob" }

Following is the query for sorting −

> db.demo365.find().sort({"FirstName":1});

This will produce the following output −

{ "_id" : ObjectId("5e57d5bad0ada61456dc9370"), "FirstName" : "Adam" }
{ "_id" : ObjectId("5e57d5c0d0ada61456dc9372"), "FirstName" : "Bob" }
{ "_id" : ObjectId("5e57d5b6d0ada61456dc936f"), "FirstName" : "Chris" }
{ "_id" : ObjectId("5e57d5bed0ada61456dc9371"), "FirstName" : "John" }

Updated on: 02-Apr-2020

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements