Convert object to array

I cannot find code to convert a nested object into an array.
From this:

 hrManager: Object
  _id: "123456789",
  name: "John Doe"

To this:

hrManager: Array
  0: Object
    _id: "123456789",
    name: "John Doe"

Using the $map does not work because it is not an array yet.
Aggregation does not work because I cannot get merge to replace the items.

db.resources.updateOne(
   { name: "J Mark" },
 [{
    $set: {
      hrManagers: {
        $objectToArray {
          $map: {
            input: "$hrManagers",
            in: {
              _id: "$$this._id",
              name: "$$this.name",
              startDate: null,
              endDate: null
            }
          }
        }
      }
    }
  }]
) 

or

 db.resources.updateOne(
  { name: "J Mark" },
  {
  $project: {
    hrManagers: [
    {
      _id: '$hrManagers._id',
      name: '$hrManagers.name'
    }
    ]
  }
  }, {
  $merge: {
    into: 'resources',
    on: 'hrManagers',
    whenMatched: 'replace'
  }
  }
 )

You can do it like this:

db.collection.update({},
[
  {
    "$set": {
      "hrManager": [
        {
          "_id": "$hrManager._id",
          "name": "$hrManager.name"
        }
      ]
    }
  }
])

Working Example

2 Likes

Try this untested snippet:

db.resources.updateOne( { "name" : "J Mark" } , [ { "$set" : {
  "hrManagers" : [
    { "_id" : "$hrManager._id"  ,
      "name" : "$hrManager.name" 
    }
  ]
} } ] )
2 Likes

Sorry @NeNaD, our answers interlaced.

2 Likes

Hahaha, same solution. Nice! :100:

2 Likes

Thank you both!

As luck would have it, I was struggling with the first set of code but the second worked fine!
The whims of a terminal session.

Thanks again!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.