Looping MongoDB collection for sorting


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

> db.demo32.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e175158cfb11e5c34d898c5")
}
> db.demo32.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e17515ccfb11e5c34d898c6")
}
> db.demo32.insertOne({"Name":"Adam"});
{
   "acknowledged" : true,
   "insertedId" : Object0Id("5e175160cfb11e5c34d898c7")
}
> db.demo32.insertOne({"Name":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e175165cfb11e5c34d898c8")
}
> db.demo32.insertOne({"Name":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e17517bcfb11e5c34d898c9")
}

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

> db.demo32.find();

This will produce the following output −

{ "_id" : ObjectId("5e175158cfb11e5c34d898c5"), "Name" : "Chris" }
{ "_id" : ObjectId("5e17515ccfb11e5c34d898c6"), "Name" : "Bob" }
{ "_id" : ObjectId("5e175160cfb11e5c34d898c7"), "Name" : "Adam" }
{ "_id" : ObjectId("5e175165cfb11e5c34d898c8"), "Name" : "John" }
{ "_id" : ObjectId("5e17517bcfb11e5c34d898c9"), "Name" : "Carol" }

Following is the query to perform sorting in MongoDB −

> db.demo32.find().sort({"Name":1});

This will produce the following output −

{ "_id" : ObjectId("5e175160cfb11e5c34d898c7"), "Name" : "Adam" }
{ "_id" : ObjectId("5e17515ccfb11e5c34d898c6"), "Name" : "Bob" }
{ "_id" : ObjectId("5e17517bcfb11e5c34d898c9"), "Name" : "Carol" }
{ "_id" : ObjectId("5e175158cfb11e5c34d898c5"), "Name" : "Chris" }
{ "_id" : ObjectId("5e175165cfb11e5c34d898c8"), "Name" : "John" }

Updated on: 02-Apr-2020

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements