MongoDB Aggregation: add field from an embedded document via a dynamic field path

Viewed 745

I have an aggregation pipeline and am stuck on a stage. At this point I have a document in the following format:

{
  _id:ObjectId(5e3d326637df7e4dda73ec22),
  levelName:"Level 1",
  levelNames: {
    "Level 1":"5e567993b6ed4b7b4d2c044d"
    "Level 2":"5e567996a7826d45f836dfa3"
    "Level 3":"5e5679991f515a01c73e9006"
  }
}

and I want to add an $addField/$set stage which gives me the ID value of the entry in the levelNames object with a key matching the levelName property of the root document.

I've been trying to use some sort of dynamic field path ($concat: ["levelNames.", "$levelName"]) but have had no luck. This is my $addField stage:

/**
 * newField: The new field name.
 * expression: The new field expression.
 */
{
  currentLevelId: {
    $let: {
      vars: {
        levelPath: {
          $concat: ["levelNames.", "$levelName"]
        }
      },
      in: {
        currentLevelId: "$$levelPath"
      }
    }
  }
}

and the result I get is:

{
  _id:ObjectId(5e3d326637df7e4dda73ec22),
  levelName:"Level 1",
  levelNames: {
    "Level 1":"5e567993b6ed4b7b4d2c044d"
    "Level 2":"5e567996a7826d45f836dfa3"
    "Level 3":"5e5679991f515a01c73e9006"
  }
  currentLevelId: {
    currentLevelId:"levelNames.Level 1"
  }
}

I'm trying to get the result of currentLevelId to be "5e567993b6ed4b7b4d2c044d", so my desired output is:

{
  _id:ObjectId(5e3d326637df7e4dda73ec22),
  levelName:"Level 1",
  levelNames: {
    "Level 1":"5e567993b6ed4b7b4d2c044d"
    "Level 2":"5e567996a7826d45f836dfa3"
    "Level 3":"5e5679991f515a01c73e9006"
  },
  currentLevelId: "5e567993b6ed4b7b4d2c044d"
}

Is there a way this can be achieved?

2 Answers

Use this one:

db.collection.aggregate([
   { $set: { data: { $objectToArray: "$levelNames" } } },
   {
      $set: {
         currentLevelId: {
            $arrayElemAt: ["$data.v", { $indexOfArray: ["$data.k", "$levelName"] }]
         }
      }
   },
   { $unset: "data" }
])

Mongo playground

Here is the aggregation query,

*

db.collection.aggregate([
    {
        $addFields: {
            warehouses: { $objectToArray: "$levelNames" }
        }
    },
    {
        $project: {
            levelName: 1,
            levelNames: 1,
            currentLevelId: {
                $filter: {
                    input: "$warehouses",
                    as: "item",
                    cond: { $eq: ["$$item.k", "$levelName"] }
                }
            },
        }
    },
    { $replaceRoot: { newRoot: { $mergeObjects: ["$$ROOT", { $arrayElemAt: ["$currentLevelId", 0] }] } } },
    {
        $project: {
            currentLevelId: "$v",
            levelName: true,
            levelNames: true,
        }
    }
])

*

Related