I need to add a missing counter field in my documents using the mongoshell (v4).
In JS I would do something like this:
const affected = await Data.findMany({ dataId: { $exists: false }}).toArray()
affected.map((d, i) => {
Data.updateOne({ _id: d._id }, { $set: { dataId: i + 1 }})
})
Is it possible to do this directly in the shell?
2
Answers
It’s almost identical.
Mongo shell provides the capability to use JavaScript code directly in the shell.
This can also be done using a single query:
See how it works on the playground example