【问题标题】:Get empty array when using pipeline in MongoDB lookup aggregation在 MongoDB 查找聚合中使用管道时获取空数组
【发布时间】:2021-11-26 21:36:11
【问题描述】:

我有 2 个收藏,如下所示

collectionA.insertOne({
    cart: [
        { product_id: ObjectId('xxx'), quantity: 10 }
    ]
})
collectionB.insertMany([
    { _id: ObjectId('xxx'), name: '', price: 1 },
    { _id: ObjectId('xyz'), name: '', price: 1 },
])

当我尝试使用 foreign/localField 进行 $lookup 时,没关系

{
  from: 'collectionB',
  localField: 'cart.product_id',
  foreignField: '_id',
  as: 'product_detail'
}

但我想切换到使用如下管道:

{
  from: 'collectionB',
  let: {pid: '$cart.product_id'},
  pipeline: [
    {
    $match: {
        $expr: {
          $eq: ['$_id', '$$pid']
        }
    }
  }],
  as: 'product_detail'
}

然后我在 product_detail 字段中收到一个空数组。 我怎样才能让它成为我的期望?

【问题讨论】:

    标签: mongodb pymongo


    【解决方案1】:

    当您使用$cart.product_id 时,您将获得一个包含_id 值的数组,然后进入$eq 您正在比较一个ObjectId 和一个数组。

    由于$in 用于了解某个值是否在数组中,因此您必须使用$in 而不是$eq 来获取像this example 这样的值。

    结果$lookup是这样的:

    {
      $lookup: {
        from: "collectionB",
        let: {pid: "$cart.product_id"},
        pipeline: [
          {
            $match: {
              $expr: {
                $in: [ //<--- here use $in
                  "$_id",
                  "$$pid"
                ]
              }
            }
          }
        ],
        as: "product_detail"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      • 2020-07-27
      • 2023-02-25
      • 2020-12-12
      • 1970-01-01
      相关资源
      最近更新 更多