MongoDB sắp xếp tài liệu theo thứ tự tự nhiên ($natural) - tức là thứ tự ghi nhận vật lý trên đĩa. Đây là thứ tự mặc định khi bạn dùng find() mà không chỉ định sort().
Cú pháp sắp xếp theo thứ tự tự nhiên:
db.yourCollectionName.find().sort({ "$natural": 1 });
Ví dụ minh họa:
Tạo collection orderDocsDemo với các tài liệu chèn lần lượt:
> db.orderDocsDemo.insertOne({"UserScore":87});
> db.orderDocsDemo.insertOne({"UserScore":98});
> db.orderDocsDemo.insertOne({"UserScore":99});
> db.orderDocsDemo.insertOne({"UserScore":67});
> db.orderDocsDemo.insertOne({"UserScore":78});
> db.orderDocsDemo.insertOne({"UserScore":91});
> db.orderDocsDemo.insertOne({"UserScore":86});
Kết quả find() mặc định (thứ tự $natural):
{ "_id" : ObjectId(...), "UserScore" : 87 }
{ "_id" : ObjectId(...), "UserScore" : 98 }
{ "_id" : ObjectId(...), "UserScore" : 99 }
{ "_id" : ObjectId(...), "UserScore" : 67 }
{ "_id" : ObjectId(...), "UserScore" : 78 }
{ "_id" : ObjectId(...), "UserScore" : 91 }
{ "_id" : ObjectId(...), "UserScore" : 86 }
Dùng sort({ "$natural": 1 }) cho kết quả y hệt thứ tự chèn.
Để sắp xếp theo trường cụ thể (ví dụ UserScore tăng dần):
> db.orderDocsDemo.find().sort({ "UserScore": 1 });
Kết quả:
{ "UserScore" : 67 }
{ "UserScore" : 78 }
{ "UserScore" : 86 }
{ "UserScore" : 87 }
{ "UserScore" : 91 }
{ "UserScore" : 98 }
{ "UserScore" : 99 }
Tóm tắt: Mặc định là $natural (thứ tự ghi). Dùng sort() để sắp xếp theo bất kỳ trường nào.