Dev_Ops
(Dev Ops)
April 9, 2021, 1:24am
1
I have the following data structure:
_id: "1234567890",
groups: [
{
"userId" : "123",
"votes" : [
{
"userId" : "abc",
"vote" : false,
}
]
},
{
"userId" : "456",
"votes" : [
{
"userId" : "def",
"vote" : true,
}
]
}
]
How can I $addToSet
or $push
to a specific nested votes
array?
I can successfully $addToSet
to the votes
array if I do the following:
db.collection.update({ _id: "1234567890"}, {$addToSet: { "groups.0.votes": { //new object data }}
How can I do the update based on the userId
that I pass in? Something like:
db.collection.update({ _id: "1234567890"}, {$addToSet: { "groups.[dynamic userId].votes": { //new object data }}
Thanks.
Hello @Dev_Ops , you need to use arrayFilters
option of the update operation to update specific element of an array based upon a condition matching the array element’s field (in your case the userId
field).
See examples from documentation: Update Specific Elements of an Array of Documents
Also, see these posts with similar questions and answers:
1 Like
Dev_Ops
(Dev Ops)
April 9, 2021, 12:49pm
3
Thanks @Prasad_Saya , arrayFilters
did the trick. The following query works for anyone who runs into this issue:
db.collection.update({ _id: "1234567890" },
{ $addToSet: { "groups.$[elem].votes": { //new object data } },
{ arrayFilters: [ { "elem.userId": "123" } ] } )
2 Likes
Dev_Ops:
userId
And the userId
field in the arrayFilters
is from the outer array field groups
.
Dev_Ops
(Dev Ops)
April 9, 2021, 1:06pm
5
That is correct @Prasad_Saya , thanks again for your help!
Stennie_X
(Stennie)
Split this topic
September 12, 2021, 12:37am
6