How do I sort natural in MongoDB?

MongoDBDatabaseBig Data Analytics

Use $natural to sort natural in MongoDB. Let us create a collection with documents −

> db.demo684.insertOne({Value:10});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea530cea7e81adc6a0b3957")
}
> db.demo684.insertOne({Value:50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea530d1a7e81adc6a0b3958")
}
> db.demo684.insertOne({Value:60});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea530d4a7e81adc6a0b3959")
}
> db.demo684.insertOne({Value:40});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea530d8a7e81adc6a0b395a")
}

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

> db.demo684.find();

This will produce the following output −

{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 }
{ "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 }
{ "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 }
{ "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }

Following is the query to sort on the basis of _id −

> db.demo684.find(). sort({'_id': 1});

This will produce the following output −

{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 }
{ "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 }
{ "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 }
{ "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }

You can also use $natural −

> db.demo684.find().sort({$natural: 1});

This will produce the following output −

{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 }
{ "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 }
{ "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 }
{ "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }
raja
Published on 14-May-2020 08:51:53
Advertisements