MongoDB aggregation $or with $elemMatch, $expr inside $lookup pipeline

橙三吉。 提交于 2021-01-05 11:50:20

问题


I have 2 collections :

Users collection :

{
    _id: ObjectId
}

Toto Collection :

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

And I'm trying to join the element of A collection which fieldA's id OR one of fieldB's id is matching with user's id with following aggregation :

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"]}}
        ]}
      }
    ]
  }
])

But in the output I'm just getting the document's where fieldA's id is matching but none of the fieldB's. What am I doing wrong?


回答1:


You need to use $in aggregation pipeline operator to check an element exists in an array :

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"
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
])

Test : MongoDB-Playground



来源:https://stackoverflow.com/questions/60550548/mongodb-aggregation-or-with-elemmatch-expr-inside-lookup-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!