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

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

Để phân tách (unwind) nhiều mảng cùng lúc và giữ tương quan index, sử dụng $unwind với includeArrayIndex. Tạo collection:

> db.demo515.insertOne({
  "details1": [ "4700100004" ],
  "details2": [ "Not Given" ],
  "Value1": [ "56", "45", "35" ],
  "Value2": [ "35", "45", "56" ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e889e51987b6e0e9d18f590") }

Hiển thị dữ liệu:

> db.demo515.find();

Kết quả - Value1 và Value2 đều có 3 phần tử:

Pipeline: Unwind Value1 với index1, Unwind Value2 với index2, Project thêm trường valid so sánh index1==index2, Match chỉ giữ valid=true:

> db.demo515.aggregate([
  { $unwind: { path: "$Value1", includeArrayIndex : "index1" } },
  { $unwind: { path: "$Value2", includeArrayIndex : "index2" } },
  { $project: {
    _id : 1, details1: 1, details2: 1, Value1: 1, Value2: 1,
    valid: { $eq: ["$index1", "$index2"] }
  }},
  { $match: { valid: true } }
]);

Kết quả - 3 cặp phần tử cùng index (0,0), (1,1), (2,2):

Giải thích: includeArrayIndex tạo trường index cho mỗi unwind. $eq: ["$index1", "$index2"] chỉ giữ cặp phần tử cùng vị trí trong mảng gốc. Kết quả là 3 tài liệu thay vì 9 (3x3 Cartesian product).