Search code examples
javascriptmongodbmongooseaggregation-frameworkdestructuring

Destructure arrays within the MongoDB aggregation pipeline


I was wondering if it was possible to destructure arrays while I am still in the MongoDB aggregation pipeline which would make my code alot neater.

For example, I have the following aggregation pipeline.

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

This gives the following results when queried:

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

In my case, because "recipientID" represents a default MongoDB id, it will always be unique. Hence I would prefer the following, where the resulting recipientID field is no longer a meaningless array

Desired results:

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

Solution

  • You can deconstruct recipientID array using $unwind in last pipeline,

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