I have a collection:
[
{
users: [user2, user4]
},
{
users: [user1, user2, user3]
},
{
users: [user1, user3, user4]
}
]
nested property "users" cannot contain the same user twice.
I find out that user2 is actually the same user as user1, so I update my documents.
My final result should look like this:
[
{
users: [user1, user4]
},
{
users: [user1, user3]
},
{
users: [user1, user3, user4]
}
]
Document1 is updated: user2 becomes user1.
Document2 is updated: user2 is removed since user1 already exists.
Document3 is not updated.
The order of the users is not important.
How can I achieve this with updateMany?
2
Answers
you can use the
$addToSet
operator to ensure unique values in the "users" array. Here’s an example using the MongoDB Node.js driver:Use
$filter
to get array without user2.$setUnion
with an array [user1] to get the finalusers
setMongo Playground
Playground does not allow usage of
updateMany
. You can ignore{multi: true}
in the playground as it is simply a workaround/alternative toupdateMany