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

Unwind (phân tách) hai mảng trong MongoDB Aggregation

Để kết hợp hai mảng theo phần tử tương ứng (zip), dùng $unwind lần lượt cho cả hai mảng, sau đó $match với $expr so sánh giá trị.

Tạo collection với 2 mảng song song:

> db.demo387.insertOne({
  "Name" : "101",
  "Details1" : [
    {Value:100, Value1:50, Value2:40},
    {Value:200},
    {Value:300}
  ],
  "Details" : [
    {Value:100, Value1:30, Value2:26},
    {Value:200},
    {Value:300}
  ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5d197022064be7ab44e7f8") }

Xem dữ liệu:

> db.demo387.find().pretty();

Aggregation unwind cả hai mảng và join theo Value:

> db.demo387.aggregate([
  { "$unwind": "$Details1" },
  { "$unwind": "$Details" },
  { "$match": { "$expr": { "$eq": ["$Details1.Value", "$Details.Value"] } } }
])

Kết quả (3 cặp khớp Value):

Cơ chế:

  1. Unwind Details1 → 3 tài liệu
  2. Unwind Details → 3×3 = 9 tài liệu (cartesian product)
  3. $match với $expr: lọc giữ cặp có Details1.Value == Details.Value

⚠️ Hiệu năng: Cartesian product có thể bùng nổ dữ liệu. Nên lọc sớm hoặc dùng $map/$zip (MongoDB 4.4+) để ghép mảng theo chỉ số.