I have this schema:{ key: [] }
. I want to convert it to { key: { foo: number } }
.
This is the query I came up with:
db.collection.update({}, [
{
"$set": {
key: { foo: 43 }
}
}
], { multi: true })
However, it updates the individual array item instead of the array as a whole. I.e. the document:
{ key: [1, 2] }
becomes :
{ key: [ { foo: 43 }, { foo: 43 } ] }
instead of:
{ key: { foo: 43 } }
.
I just want to get rid of the original array completely. I can just remove the field, then write the update. But is there a way to do it in one fell swoop?
Update: I have to use the pipeline, there’re other stuff going on.
2
Answers
As per this comment:
In that case, don’t use the pipeline syntax for update. So you only need to remove the
[...]
surrounding$set
:And if you do need an update pipeline for some other steps, then unset
key
before setting a new value:Mongo Playground
Use
$literal
Mongo Playground