无法在收集之间 mongodb 收到预期结果

Not able to receive expected result in mongodb between collections

我正在尝试在产品列表本身中获取包含已登录用户愿望清单的产品列表。我正在尝试 $lookup 但没有得到预期的结果。

产品文档:

[
{
    "_id" : ObjectId("6044351794bee8b6e0fce48f"),
    "sku" : "P003474",
    "name" : "Kitchen Wash"
},
{
    "_id" : ObjectId("6085584c42ad3c58c5dbc6b7"),
    "sku" : "TS0012",
    "name" : "T-shirt"
},
{
    "_id" : ObjectId("608d20a90e629fcc0d3a93e1"),
    "sku" : "Apple1101",
    "name" : "Green Apple"
}
]

心愿单文件:

wishlist:

[
{
    "_id" : ObjectId("608d8af12b7556c445f5cd87"),
    "product" : ObjectId("6044351794bee8b6e0fce48f"),
    "user" : ObjectId("601fb31a60e0a024143e6ea3"),
    "isLiked" : false
},
{
    "_id" : ObjectId("608d8bad2b7556c445f5cd88"),
    "product" : ObjectId("6085584c42ad3c58c5dbc6b7"),
    "user" : ObjectId("601fb31a60e0a024143e6ea3"),
    "isLiked" : true
}
]

预期结果:

预期输出:

[
{
    "_id" : ObjectId("6044351794bee8b6e0fce48f"),
    "sku" : "P003474",
    "name" : "Kitchen Wash",
    "isLiked": false
},
{
    "_id" : ObjectId("6085584c42ad3c58c5dbc6b7"),
    "sku" : "TS0012",
    "name" : "T-shirt",
    "isLiked": true
},
{
    "_id" : ObjectId("608d20a90e629fcc0d3a93e1"),
    "sku" : "Apple1101",
    "name" : "Green Apple"
}
]

我正在尝试的查询:

db.getCollection('products').aggregate([
  {
    $lookup: {
      from: "wishlists",
      localField: "_id",
      foreignField: "product",
      as: "product"
    }
  },
  {
    $unwind:"$product"
  }
])

无法得到上面声明的结果

  • $unwind 导致问题,第一个问题是当 product 查找结果为空时它将删除文档/[] 如果您不指定 preserveNullAndEmptyArrays : true,请参阅 playground
  • 使用 $lookup 管道并匹配产品 ID 和用户 ID 条件
  • 我在 $lookup
  • 中将 as 名称更改为 isLiked
  • $addFields 添加 isLiked 参数,$arrayElemAt 从第一个元素 isLiked 获取元素
db.getCollection('products').aggregate([
  {
    $lookup: {
      from: "wishlists",
      let: { product: "$_id" },
      pipeline: [
        {
          $match: {
            $and: [
              { $expr: { $eq: ["$$product", "$product"] } },
              { user: ObjectId("601fb31a60e0a024143e6ea3") }
            ]
          }
        }
      ],
      as: "isLiked"
    }
  },
  {
    $addFields: {
      isLiked: { $arrayElemAt: ["$isLiked.isLiked", 0] }
    }
  }
])

Playground