Sử dụng sort() để sắp xếp, kết hợp projection để chỉ hiển thị trường cần thiết. Tạo collection:
> db.demo611.insertOne({"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e987110f6b89257f5584d83") }
> db.demo611.insertOne({"Name":"Adam"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e987115f6b89257f5584d84") }
> db.demo611.insertOne({"Name":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e987118f6b89257f5584d85") }
> db.demo611.insertOne({"Name":"Bob"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e98711bf6b89257f5584d86") }
Hiển thị mặc định:
> db.demo611.find();
Sắp xếp theo Name tăng dần (1):
> db.demo611.find().sort({Name:1});Kết quả (Adam → Bob → Chris → John):
Chỉ hiển thị trường Name (ẩn _id):
db.demo611.find().sort({Name:1}).project({Name:1, _id:0})hoặcdb.demo611.find({}, {Name:1, _id:0}).sort({Name:1}).Lưu ý MongoDB 4: sort() dùng index nếu có, ngược lại sort trong bộ nhớ (giới hạn 32MB). Nên tạo index trên trường sort thường xuyên.