Iterating an object and fetching all the keys and setting them to a new field in aggregation framework

Viewed 72

I have an object where I have a key whose value is an object. I would like to add a new field into a document which contains the name of all the keys.

Sample object:

{
   heros: {
       superman: 51,
       batman: 89,
       ironman: 95,
   }
}

Expected output after doing a $addField:

{
   heros: {
       superman: 51,
       batman: 89,
       ironman: 95,
   }
   allHeros: ['superman', 'batman', 'ironman'],
}
1 Answers
  • $objectToArray convert heros object to array key-value format
  • $map to iterate loop of above converted array and return key
db.collection.aggregate([
  {
    $addFields: {
      allHeros: {
        $map: {
          input: { $objectToArray: "$heros" },
          in: "$$this.k"
        }
      }
    }
  }
])

Playground


There is second option as well,

  • $objectToArray convert heros object to array key-value format
  • just use allHeros.k and it will return array of keys
db.collection.aggregate([
  {
    $addFields: {
      allHeros: { $objectToArray: "$heros" }
    }
  },
  {
    $addFields: {
      allHeros: "$allHeros.k"
    }
  }
])

Playground

Related