I have an existing collection, containing several documents:
[{
"_id": "1",
"someArray": [
{
"_id": "1.1"
"color": "RED"
},
{
"_id": "1.2"
"color": "GREEN"
},
{
"_id": "1.3"
"color": "GREEN"
}
]
}, {
"_id": "2",
"someArray": [
{
"_id": "2.1"
"color": "WHITE"
},
{
"_id": "2.2"
"color": "BLUE"
}
]
}, // many others here...
]
I need to replace the color
field of the sub-elements by a colors
field, which is an array containing the same value color
did.
Here is the result I want to obtain:
[{
"_id": "1",
"someArray": [
{
"_id": "1.1"
"colors": [ "RED" ]
},
{
"_id": "1.2"
"colors": [ "GREEN" ]
},
{
"_id": "1.3"
"colors": [ "GREEN" ]
}
]
}, {
"_id": "2",
"someArray": [
{
"_id": "2.1"
"colors": [ "WHITE" ]
},
{
"_id": "2.2"
"colors": [ "BLUE" ]
}
]
}]
My closest attempt was this:
collection.updateMany(
Filters.ne("someArray", Collections.emptyList()),
Updates.combine(
Updates.set("someArray.$[].colors", "[ $someArray.color ]"),
Updates.unset("someArray.$[].color")
)
);
But the value of colors
is inserted as a String, as-is. It’s not interpreted as "an array containing the value of color
field".
This has to be done in Java. Please don’t provide JS-based solution.
2
Answers
The solution I finally came up with...
As suggested in the comment section, I am afraid this can be done with a simple update query, however, if you are using
MongoDB version 4.2
and above, you can use$merge
to your advantage, to generate your updated document and merge it in the existing collection like this:Here is the working, mongo shell equivalent pipeline.