Kết hợp $group với $addToSet để lấy giá trị duy nhất
Sử dụng pipeline aggregation với $group và $addToSet để vừa nhóm dữ liệu, vừa lấy các giá trị distinct (không trùng lặp) trong một truy vấn duy nhất.
Dữ liệu học sinh
> db.demo16.insertOne({ "StudentName": "Chris", "StudentSection": "A", "StudentAge": 23, "StudentMarks": 47 });
> db.demo16.insertOne({ "StudentName": "Bob", "StudentSection": "B", "StudentAge": 21, "StudentMarks": 85 });
> db.demo16.insertOne({ "StudentName": "Carol", "StudentSection": "A", "StudentAge": 26, "StudentMarks": 97 });
Pipeline aggregation
> db.demo16.aggregate([
{
$group: {
_id: null,
StudentName: { $addToSet: "$StudentName" },
StudentSection: { $addToSet: "$StudentSection" },
StudentMinimumAge: { $min: "$StudentAge" },
StudentMaximumAge: { $max: "$StudentAge" },
StudentMinimumMarks: { $min: "$StudentMarks" },
StudentMaximumMarks: { $max: "$StudentMarks" }
}
}
]).pretty();
Kết quả
{
"_id": null,
"StudentName": ["Carol", "Bob", "Chris"],
"StudentSection": ["B", "A"],
"StudentMinimumAge": 21,
"StudentMaximumAge": 26,
"StudentMinimumMarks": 47,
"StudentMaximumMarks": 97
}
Giải thích: $addToSet tự động loại bỏ trùng lặp. _id: null nhóm toàn bộ collection thành một nhóm duy nhất.