I have the following record:
id: 119,
customfields: Array (2)
0: Object
value: "Mr"
type: "salutation"
1: Object
value: "Google"
type: "company"
I need to update this document so that I get:
id: 119,
salutation: "Mr",
company: "Google"
Important is:
- The position of the arguments can vary, ie, some records have
salutation
first, others havecompany
and other may have other fields that do not matter. - some documents do not have the
salutation
records inside thecustomfields
array and therefore should just be ignored. Same logic for the company.
2
Answers
$map
customfields
to an array of k-v tuple first. Then,$mergeObjects
with$$ROOT
object to get the final object.$unset
the now useless customfields and$merge
byid
to update back to the document.Mongo Playground
Here’s another way to do it using
"$reduce"
to rebuild the document.Try it on mongoplayground.net.