Starting `Mongo 4.2`, [`db.collection.update()`](
[To see links please register here]
) can accept an aggregation pipeline, finally allowing the update of a field based on its own value:
// { general: { files: { file: [
// { version: { software_program: "MonkeyPlus", indentifier: "6.0.0" } }
// ] } } }
db.collection.updateMany(
{},
[{ $set: { "general.files.file": {
$map: {
input: "$general.files.file",
as: "file",
in: {
version: {
software_program: "$$file.version.software_program",
identifier: "$$file.version.indentifier" // fixing the typo here
}
}
}
}}}]
)
// { general: { files: { file: [
// { version: { software_program: "MonkeyPlus", identifier: "6.0.0" } }
// ] } } }
---
Literally, this `update`s documents by (re)`$set`ting the `"general.files.file"` array by `$map`ping its `"file"` elements `in` a `"version"` object containing the same `"software_program"` field and the renamed `"identifier"` field which contains what used to be the value of `"indentifier"`.
---
A couple additional details:
* The first part `{}` is the match query, filtering which documents to update (in this case all documents).
* The second part `[{ $set: { "general.files.file": { ... }}}]` is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline):
* [`$set`](
[To see links please register here]
) is a new aggregation operator which in this case replaces the value of the `"general.files.file"` array.
* Using a [`$map`](
[To see links please register here]
) operation, we replace all elements from the `"general.files.file"` array by basically the same elements, but with an `"identifier"` field rather than `"indentifier"`:
* `input` is the array to map.
* `as` is the variable name given to looped elements
* `in` is the actual transformation applied on elements. In this case, it replaces elements by a `"version"` object composed by a `"software_program"` and a `"identifier"` fields. These fields are populated by extracting their previous values using the `$$file.xxxx` notation (where `file` is the name given to elements from the `as` part).