$set field to first element of its previous array value

I want to replace a the field name with the first element of its current value.

Below is an example database

[
  {
    _id: "ABC",
    name: [
      "foo",
      "bar",
      "lorem",
      "ipsum"
    ]
  },
  {
    _id: "DEF",
    name: [
      "bar",
      "foo",
      "something"
    ]
  }
]

the name for id ABC for example should have its name field changed to “foo” and DEF should become “bar”

Below is the query I have so far

db.collection.update({
  name: {
    $type: "array"
  }
},
[
  {
    $set: {
      "name": "new name here"
    }
  }
],
{
  multi: true
})

You can make use of:

Something like this?

db.getCollection("Test").updateMany(
{},
[
    {
        $set:{
            name:{
                $arrayElemAt:['$name', 0]
            }
        }
    }
]
)

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