簡體   English   中英

在 MongoDB 聚合管道中解構數組

[英]Destructure arrays within the MongoDB aggregation pipeline

我想知道是否有可能在我仍在 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"
        }
    }

您可以在最后一個管道中使用$unwind解構recipientID數組,

await User.aggregate([
      ... // your all pipelines

      // add this line
      { $unwind: "$chatLogs.recipientID" }
]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM