Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Lấy giá trị distinct có sắp xếp trong MongoDB

Phương thức distinct() trả về mảng giá trị duy nhất. Có thể chain .sort() để sắp xếp kết quả.

Cú pháp:

db.yourCollectionName.distinct("yourFieldName").sort();

Ví dụ: Collection getDistinctWithSortedDataDemo có dữ liệu trùng lặp:

> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":10,"StudentName":"John","StudentAge":23});
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":20,"StudentName":"Carol","StudentAge":21});
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":10,"StudentName":"John","StudentAge":23}); // trùng
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":30,"StudentName":"Chris","StudentAge":22});
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":20,"StudentName":"Carol","StudentAge":21}); // trùng
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":40,"StudentName":"Bob","StudentAge":20});
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":40,"StudentName":"Bob","StudentAge":20}); // trùng

Distinct StudentName (mặc định không sắp xếp):

> db.getDistinctWithSortedDataDemo.distinct("StudentName");
// [ "John", "Carol", "Chris", "Bob" ] (thứ tự không đảm bảo)

Distinct StudentName có sắp xếp:

> db.getDistinctWithSortedDataDemo.distinct("StudentName").sort();
// [ "Bob", "Carol", "Chris", "John" ]

Distinct StudentAge có sắp xếp:

> db.getDistinctWithSortedDataDemo.distinct("StudentAge").sort();
// [ 20, 21, 22, 23 ]

Lưu ý: distinct() trả về mảng JavaScript, .sort() là method của Array (sắp xếp theo Unicode mặc định). Với số, sort() mặc định chuyển thành string, cần .sort((a,b)=>a-b) để sort số đúng. Trong shell MongoDB, .sort() trên mảng số hoạt động đúng vì shell xử lý đặc biệt.