'Collect as a Set certain values from Document in Update?
Morning,
When trying to update a Document in MongoDB I'm trying to collect certain specified fields as a set, without non repeated items, and was wondering if this is achievable within the update clause in updateMany, I was trying with $addToSet but no luck so far.
I'm trying to do as follows:
getCollection(...).updateMany(
and(neq("sample_field", "SAMPLE")),
..., // Replace "array" also including "field_a" and "field_b" without having repated elements.
new UpdateOptions().upsert(true)
);
Having as input:
{"_id": 1, "field_a": "a", "field_b": "b", "field_c": "c", "array": ["c"]}
{"_id": 2, "field_a": "b", "field_b": "b", "field_c": "c", "array": ["c"]}
After running the update (including field_a and field_b in array) the output should be:
{"_id": 1, "field_a": "a", "field_b": "b", "field_c": "c", "array": ["a", "b", "c"]}
{"_id": 2, "field_a": "b", "field_b": "b", "field_c": "c", "array": ["b", "c"]}
Thanks in advance!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
