Khi có giá trị null, triển khai ORDERBY bằng sort(). Lưu ý: Từ MongoDB v3.2, toán tử $orderby đã deprecated trong mongo shell, hãy dùng cursor.sort().
Tạo collection có giá trị null:
> db.demo530.insertOne({"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2990ef4dcbee04fbbbec") }
> db.demo530.insertOne({"Name":null});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2991ef4dcbee04fbbbed") }
> db.demo530.insertOne({"Name":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2992ef4dcbee04fbbbee") }
> db.demo530.insertOne({"Name":"Adam"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2995ef4dcbee04fbbbef") }
> db.demo530.insertOne({"Name":null});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b2999ef4dcbee04fbbbf0") }
> db.demo530.insertOne({"Name":"Carol"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8b299eef4dcbee04fbbbf1") }
Hiển thị dữ liệu (null xen kẽ):
> db.demo530.find();
Kết quả:
Sử dụng aggregation với
$matchlọc tồn tại trường Name,$sorttăng dần (1):> db.demo530.aggregate([ {$match: {"Name": {$exists: true}}}, {$sort: { "Name": 1}} ]);Kết quả - null xuất hiện TRƯỚC các chuỗi (theo thứ tự BSON):
Thứ tự sắp xếp BSON: null < số < chuỗi < object < array < binary < ObjectId < boolean < Date < regex. Để null cuối cùng, dùng
$sort: { Name: { $meta: "textScore" } }hoặc xử lý ở application layer.