Sử dụng $natural để sắp xếp theo thứ tự tự nhiên (thứ tự lưu trữ vật lý/điền vào) trong MongoDB.
Tạo collection 4 tài liệu:
> 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") }
Hiển thị tất cả (thứ tự chèn):
> db.demo684.find();
Sắp xếp theo _id tăng dần (1):
> db.demo684.find().sort({'_id': 1});
Sắp xếp tự nhiên với $natural: 1 (cho cùng kết quả vì chưa có xóa/cập nhật):
> db.demo684.find().sort({$natural: 1});
Kết quả (cả hai cách cho thứ tự: 10, 50, 60, 40):
{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 }
{ "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 }
{ "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 }
{ "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }
Lưu ý: $natural trả về theo thứ tự vật lý trên đĩa. Thường trùng với _id nếu không có xóa/cập nhật làm phân mảnh.