嵌套数组中的$ lookup

詹姆士

我需要一个MongoDB查询来从事件,用户和确认的集合中返回聚合结果。

db.events.aggregate([
  {
    "$match": {
      "_id": "1"
    }
  },
  {
    "$lookup": {
      "from": "confirmations",
      "as": "confirmations",
      "let": {
        "eventId": "$_id"
      },
      "pipeline": [
        {
          "$match": {
            "$expr": {
              "$eq": [
                "$eventId",
                "$$eventId"
              ]
            }
          }
        },
        {
          "$lookup": {
            "from": "users",
            "as": "user",
            "let": {
              "userId": "$confirmations.userId"
            },
            "pipeline": [
              {
                "$match": {
                  "$expr": {
                    "$eq": [
                      "$_id",
                      "$$userId"
                    ]
                  }
                }
              },
              
            ]
          },
          
        },
        
      ]
    }
  }
])

期望的

[
  {
    "_id": "1",
    "confirmations": [
      {
        "_id": "1",
        "eventId": "1",
        "user": {
          "_id": "1",
          "name": "X"
        },
        "userId": "1"
      },
      {
        "_id": "2",
        "eventId": "1",
        "user": {
          "_id": "2",
          "name": "Y"
        },
        "userId": "2"
      }
    ],
    "title": "foo"
  }
]

除了确认数组中的嵌入式用户,其他所有东西都可以正常工作。我需要输出来显示confirmations.user,而不是一个空数组。

游乐场:https ://mongoplayground.net/p/jp49FW59WCv

Dheemanth bhat

您在inner的变量声明中犯了错误$lookup试试这个解决方案:

db.events.aggregate([
    {
        "$match": {
            "_id": "1"
        }
    },
    {
        $lookup: {
            from: "confirmations",
            let: { "eventId": "$_id" },
            pipeline: [
                {
                    $match: {
                        "$expr": {
                            $eq: ["$eventId", "$$eventId"]
                        }
                    }
                },
                {
                    $lookup: {
                        from: "users",
                        let: { "userId": "$userId" },
                        pipeline: [
                            {
                                $match: {
                                    $expr: {
                                        $eq: ["$_id", "$$userId"]
                                    }
                                }
                            }
                        ],
                        as: "user"
                    }
                },
                { $unwind: "$user" }
            ],
            as: "confirmations"
        }
    }
])

此外代替$unwinduser内内$lookup,你可以使用:

{
    $addFields: {
        user: { $arrayElemAt: ["$user", 0] }
    }
}

因为$unwind默认情况下不会保留前一阶段的空结果。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章