Mongo updateMany with $set agreggation, self reference and array member gives empty array

Viewed 103

With Mongo 4.2.5 and this collection

db.foo.insert({foo:["bar", "baz"]})

when trying to copy the "baz" in the array to a new field named foobaz like this in the shell:

db.foo.updateMany({}, [{$set:{foobaz: "$foo.1"}}])

I get an object like this

{
   _id: fooid,
   foo: ["bar", "baz"],
   foobaz: []//empty array instead of "baz"
}

What am i doing wrong ?

1 Answers

You need $arrayElemAt since $set requires Aggregation Framework's array access syntax:

db.foo.updateMany({}, [{$set:{foobaz: { $arrayElemAt: [ "$foo", 1 ] }}}])
Related