Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/449.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在MongoDB聚合管道中分解阵列_Javascript_Mongodb_Mongoose_Aggregation Framework_Destructuring - Fatal编程技术网

Javascript 在MongoDB聚合管道中分解阵列

Javascript 在MongoDB聚合管道中分解阵列,javascript,mongodb,mongoose,aggregation-framework,destructuring,Javascript,Mongodb,Mongoose,Aggregation Framework,Destructuring,我想知道,当我还在MongoDB聚合管道中时,是否有可能对数组进行分解,这将使我的代码更加整洁 例如,我有以下聚合管道 await User.aggregate([ { $match: { _id: userID } }, { $project: { chatLogs: 1, username: 1, profilePicURL: 1 }, }, { $unwind: "$chatLogs" }, {

我想知道,当我还在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,所以它总是唯一的。因此,我更喜欢下面的方法,其中得到的recipientID字段不再是一个无意义的数组

预期结果:

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