MongoDB聚合$或$lookup管道中的$elemMatch、$expr



我有两个集合:

用户集合:

{
    _id: ObjectId
}

Toto系列:

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

我正在尝试加入一个集合的元素,该集合的fieldA的idfield B的id之一用户的id匹配,聚合如下:

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的id匹配。我做错了什么?

您需要使用$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

最新更新