MongoDB 查找匹配数组中的两个元素

MongoDB lookup match two elements in array

我有一个用户集合,其文档如下所示:

{
      "name": "James",
      "participations": [
        {
          participant_id: 1,
          participant_type: "Board",
          // other fields
        },
        {
          participant_id: 2,
          participant_type: "Team"
          // other fields
        }
      ]
    },

我正在汇总一个用户集合:

db.boards.aggregate([
  { '$match' => { _id: 65 } },
  { '$lookup' => 
        { from: "users", as: "users",
          let: { "board_id": "$_id" },
          pipeline: [
            { '$match' =>
               { '$expr' => {
                 '$and' => [
                    { '$in' => ["Board", "$participations.participant_type"] },
                    { '$in' => ["$$board_id", "$participations.participant_id"] }, 
                 ]
              }}
            }
          ],
        } 
      },
])

然而,上述逻辑是有缺陷的。如果用户参与了 ID 为 65 的团队,那么该用户将出现,即使他没有参与看板。

我想select所有参与participant_type“董事会”和participant_id65的用户。我尝试使用elemMatch,但显然聚合框架不支持?

如果您对 participations 数组中的每个元素都不感兴趣,可以通过 $unwinding participations 字段来实现您的目标。这将为数组中的每个元素提供一个文档,然后您可以像这样进行匹配:

pipeline: [
            { '$unwind' => '$participations' },
            { '$match' =>
               { '$expr' => {
                 '$and' => [
                    { '$eq' => ["Board", "$participations.participant_type"] },
                    { '$eq' => ["$$board_id", "$participations.participant_id"] }, 
                 ]
              }}
            }
          ]