Search code examples
arraysmongodbmongoosemongodb-querymongodb-update

MongoDB - Update with $set and $first operators


I'm trying to update a field with the first element of an array.

The model:

{
    name: { type: ObjectId },
    names: { type: [ObjectId] }
}

The request:

Model.updateMany({}, 
            {
                $set: {
                    name: {
                        $first: '$names',
                    },
                },
            })

But I'm getting an error:

Cast to ObjectId failed for value "{ '$first': '$names' }" (type Object) at path "name" because of "BSONTypeError"

Do you know another way to set a field with the value of the first element of an array? Should I use aggregate instead?


Solution

  • You need to update with aggregation pipeline.

    Model.updateMany({},
    [
      {
        $set: {
          name: {
            $first: '$names',
          },
        },
      }
    ])