Project array elements as individual fields

Viewed 137

I have a collection with a field in each document that looks like:

{
   person = [{"name":"Alex"},{"name":"Betsy"},{"name":"Chauncy"}]
}

Documents can have different length for this array I'm trying to project the individual element of this array as fields within the same document with the key as Name {index} and the corresponding value for the name. I can't seem to generate the projected fields given an array.

Expected output:

[{
"name1": "Alex",
"name2": "Betsy",
"name3": "Chauncy"
}]
1 Answers

You can use aggregation

  • $unwind to deconstruct the array and it helps to get the index too
  • $group to reconstruct the array with key (k): value(v) pair which helps in next stage
  • $arrayToObject since group already made k:v pair, this helps to make array to opbect
  • $replaceRoot helps to make the object as root

Here is the code

db.collection.aggregate([
  {
    $unwind: { path: "$person", includeArrayIndex: "index" }
  },  
  {
    $group: {
      _id: null,
      person: {
        $push: {
          k: { "$concat": [ "name", { $toString: "$index" } ] },
          v: "$person.name"
        }
      }
    }
  },
  {
    $project: {
      person: { "$arrayToObject": "$person" }
    }
  },
  {
    "$replaceRoot": { "newRoot": "$person" }
  }
])

Working Mongo playground

Related