Phương thức sort() sắp xếp kết quả truy vấn theo một hoặc nhiều trường. Tham số là đối tượng: {trường: 1} tăng dần, {trường: -1} giảm dần.
Tạo collection:
> db.demo32.insertOne({"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e175158cfb11e5c34d898c5") }
> db.demo32.insertOne({"Name":"Bob"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e17515ccfb11e5c34d898c6") }
> db.demo32.insertOne({"Name":"Adam"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e175160cfb11e5c34d898c7") }
> db.demo32.insertOne({"Name":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e175165cfb11e5c34d898c8") }
> db.demo32.insertOne({"Name":"Carol"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e17517bcfb11e5c34d898c9") }
Xem dữ liệu gốc:
> db.demo32.find();
{ "_id" : ObjectId("5e175158cfb11e5c34d898c5"), "Name" : "Chris" }
{ "_id" : ObjectId("5e17515ccfb11e5c34d898c6"), "Name" : "Bob" }
{ "_id" : ObjectId("5e175160cfb11e5c34d898c7"), "Name" : "Adam" }
{ "_id" : ObjectId("5e175165cfb11e5c34d898c8"), "Name" : "John" }
{ "_id" : ObjectId("5e17517bcfb11e5c34d898c9"), "Name" : "Carol" }
Sắp xếp theo Name tăng dần (A-Z):
> db.demo32.find().sort({"Name":1});
Kết quả:
{ "_id" : ObjectId("5e175160cfb11e5c34d898c7"), "Name" : "Adam" }
{ "_id" : ObjectId("5e17515ccfb11e5c34d898c6"), "Name" : "Bob" }
{ "_id" : ObjectId("5e17517bcfb11e5c34d898c9"), "Name" : "Carol" }
{ "_id" : ObjectId("5e175158cfb11e5c34d898c5"), "Name" : "Chris" }
{ "_id" : ObjectId("5e175165cfb11e5c34d898c8"), "Name" : "John" }
Mẹo hiệu năng: Tạo index trên trường sắp xếp để tránh quét toàn bộ collection (in-memory sort limit 32MB).