【问题标题】:MongoDB aggregation $or with $elemMatch, $expr inside $lookup pipelineMongoDB 聚合 $or 与 $elemMatch, $expr 在 $lookup 管道中
【发布时间】:2020-03-05 17:01:45
【问题描述】:

我有 2 个收藏:

用户集合:

{
    _id: ObjectId
}

多多收藏:

{
    _id: ObjectId
    fieldA: {_id: ObjectId}
    fieldB: [{_id: ObjectId}, {_id: ObjectId}]
}

我正在尝试加入 fieldA 的 idfieldB 的 id 之一与 user's id 匹配的 A 集合的元素以下聚合:

db.users.aggregate([
{
  $lookup: {
    from: "Toto",
    let: { "user_id": "$_id" },
    as: "fcollection",
    pipeline: [
      { $match:  
        {$or:[
          {"fieldB": {$elemMatch: {"_id": "$$user_id"}}}, 
          {$expr: {$eq :["$fieldA._id", "$$user_id"]}}
        ]}
      }
    ]
  }
])

但在输出中,我只是获得了与 fieldA 的 id 匹配但没有 fieldB 匹配的文档。我做错了什么?

【问题讨论】:

    标签: mongodb mongodb-query nosql aggregation-framework


    【解决方案1】:

    您需要使用$in聚合管道运算符来检查数组中是否存在元素:

    db.users.aggregate([
      {
        $lookup: {
          from: "Toto",
          let: {
            "user_id": "$_id"
          },
          as: "fcollection",
          pipeline: [
            {
              $match: {
                $or: [
                  {
                    $expr: {
                      $in: [
                        "$$user_id",
                        "$fieldB._id"
                      ]
                    }
                  },
                  {
                    $expr: {
                      $eq: [
                        "$fieldA._id",
                        "$$user_id"
                      ]
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    ])
    

    测试: MongoDB-Playground

    【讨论】:

    • 非常感谢!!你只是让我从一个非常糟糕的头痛中解脱出来......最后一件事:如何在使用 $in 运算符之前检查数组是否存在?
    • @Dave : 所以你需要使用$cond 来检查fieldB 是否是一个数组,如果是则执行$in 操作,如果不是返回false,请检查这个:: mongoplayground.net/p/a9azKLDceMZ
    猜你喜欢
    • 2018-07-21
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2020-08-12
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多