【问题标题】:Destructure arrays within the MongoDB aggregation pipeline在 MongoDB 聚合管道中解构数组
【发布时间】:2020-12-12 00:42:13
【问题描述】:

我想知道是否可以在我仍在 MongoDB 聚合管道中时解构数组,这会使我的代码更整洁。

例如,我有以下聚合管道。

await User.aggregate([
      { $match: { _id: userID } },
      {
        $project: { chatLogs: 1, username: 1, profilePicURL: 1 },
      },
      { $unwind: "$chatLogs" },
      {
        $lookup: {
          from: "users",
          let: { recipientID: "$chatLogs.recipientID" },
          pipeline: [
            {
              $match: { $expr: { $eq: ["$_id", "$$recipientID"] } },
            },
            { $project: { profilePicURL: 1 } },
          ],
          as: "chatLogs.recipientID",
        },
      },
    ]);

查询时会给出以下结果:

{
        "_id": "5f2ffb54eea9c2180a732afa",
        "username": "joe",
        "profilePicURL": "/images/profile/default_profile.png",
        "chatLogs": {
            "recipientID": [
                {
                    "_id": "5f2faf5ad18a76073729f475",
                    "profilePicURL": "/images/profile/default_profile.png"
                }
            ],
            "chat": "5f30b6c3d117441c2abda1ba"
        }
    }

在我的例子中,因为“recipientID”代表一个默认的 MongoDB id,它总是唯一的。因此,我更喜欢以下内容,其中生成的收件人 ID 字段不再是无意义的数组

期望的结果:

{
        "_id": "5f2ffb54eea9c2180a732afa",
        "username": "joe",
        "profilePicURL": "/images/profile/default_profile.png",
        "chatLogs": {
            "recipientID": {
                    "_id": "5f2faf5ad18a76073729f475",
                    "profilePicURL": "/images/profile/default_profile.png"
                }
            "chat": "5f30b6c3d117441c2abda1ba"
        }
    }

【问题讨论】:

    标签: javascript mongodb mongoose aggregation-framework destructuring


    【解决方案1】:

    您可以在最后一个管道中使用$unwind 解构recipientID 数组,

    await User.aggregate([
          ... // your all pipelines
    
          // add this line
          { $unwind: "$chatLogs.recipientID" }
    ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2020-09-20
      相关资源
      最近更新 更多