Updating nested array of objects using $addToSet

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

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

And the userId field in the arrayFilters is from the outer array field groups.

That is correct @Prasad_Saya, thanks again for your help!

8 posts were split to a new topic: Is it possible to set the new object data depending on the actual element in $addToSet?