Để lấy danh sách tất cả giá trị distinct (unique) của một trường trong MongoDB, bạn sử dụng phương thức distinct().
Cú pháp
db.yourCollectionName.distinct("yourFieldName");
Ví dụ minh họa
Tạo collection và dữ liệu
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[10,20,30]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8fc89ed3c9d04998abf011") }
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[40,50,60]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8fc8abd3c9d04998abf012") }
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[10,20,30]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8fc8d7d3c9d04998abf013") }
> db.listAllValuesOfCeratinFieldsDemo.insertOne({"ListOfValues":[40,50,70]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8fc8e2d3c9d04998abf014") }
Xem tất cả documents
> db.listAllValuesOfCeratinFieldsDemo.find().pretty();
{
"_id" : ObjectId("5c8fc89ed3c9d04998abf011"),
"ListOfValues" : [ 10, 20, 30 ]
}
{
"_id" : ObjectId("5c8fc8abd3c9d04998abf012"),
"ListOfValues" : [ 40, 50, 60 ]
}
{
"_id" : ObjectId("5c8fc8d7d3c9d04998abf013"),
"ListOfValues" : [ 10, 20, 30 ]
}
{
"_id" : ObjectId("5c8fc8e2d3c9d04998abf014"),
"ListOfValues" : [ 40, 50, 70 ]
}
Lấy distinct values của trường ListOfValues
> db.listAllValuesOfCeratinFieldsDemo.distinct("ListOfValues");
[ 10, 20, 30, 40, 50, 60, 70 ]
Kết quả gom tất cả giá trị unique từ các mảng: 10,20,30 (doc 1,3) + 40,50,60 (doc 2) + 40,50,70 (doc 4) = 7 giá trị duy nhất.
Đặc điểm của distinct() trên mảng
- Tự động flatten mảng: lấy từng phần tử
- Loại bỏ trùng lặp:
distinct= unique values - Trả về mảng các giá trị
Distinct với điều kiện (query filter)
// Chỉ distinct của document thỏa mãn điều kiện
db.collection.distinct("fieldName", { status: "active" });
Lưu ý hiệu năng
distinct()quét collection → tạo index trên trường để tăng tốc- Kết quả trả về là array trong RAM → cẩn thận với field cardinality cao (nhiều giá trị unique)
- Giới hạn 16MB cho kết quả distinct (BSON document size limit)
Thay thế bằng Aggregation (linh hoạt hơn)
db.listAllValuesOfCeratinFieldsDemo.aggregate([
{ $unwind: "$ListOfValues" },
{ $group: { _id: "$ListOfValues" } },
{ $sort: { _id: 1 } },
{ $project: { _id: 0, value: "$_id" } }
])
Cho phép: filter ($match), sort, limit, pagination, format output tùy ý.