MongoDB में natural sort के लिए $natural का उपयोग करें।
Collection बनाना
> 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") }
सभी Documents Display करना
> db.demo684.find();
Output (insertion order):
{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 }
{ "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 }
{ "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 }
{ "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }
_id द्वारा Sort Query
> db.demo684.find(). sort({'_id': 1});
Output (same as insertion order क्योंकि ObjectId timestamp based होता है):
{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 }
{ "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 }
{ "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 }
{ "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }
$natural Sort Query
> db.demo684.find().sort({$natural: 1});
Output:
{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 }
{ "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 }
{ "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 }
{ "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }
व्याख्या: $natural: 1 documents को physical storage order (insertion order) में return करता है। $natural: -1 reverse order में return करता है। Capped collections में यह guaranteed insertion order देता है।