Phát hiện giá trị trùng lặp trong nested array bằng $unwind và $group
Kết hợp $unwind (phẳng mảng) và $group (đếm) để tìm giá trị trùng lặp trong mảng lồng sâu.
Dữ liệu có trùng Name="Chris"
> db.demo347.insertOne({ details: { details1: [{ Name: "Chris", Age: 21 }] } });
> db.demo347.insertOne({ details: { details1: [{ Name: "David", Age: 22 }] } });
> db.demo347.insertOne({ details: { details1: [{ Name: "Chris", Age: 21 }] } });
Pipeline phát hiện trùng lặp
> db.demo347.aggregate([
{ $unwind: "$details" },
{ $unwind: "$details.details1" },
{ $group: { _id: "$details.details1.Name", count: { $sum: 1 } } },
{ $match: { _id: { $ne: null }, count: { $gt: 1 } } }
]);
Kết quả
{ "_id": "Chris", "count": 2 }
Giải thích:
$unwind: "$details": Phẳng mảng details (1 phần tử/doc)$unwind: "$details.details1": Phẳng mảng details1$group: Nhóm theo Name, đếm số lần xuất hiện$match: Lọc count > 1 (trùng lặp) và _id không null