How to update Meteor array element inside a document

I have a Meteor Mongo document as shown below

{
	"_id" : "zFndWBZTvZPgSKXHP",
	"activityId" : "aRDABihAYFoAW7jbC",
	"activityTitle" : "Test Mongo Document",
	"users" : [
		{
			"id" : "b1@gmail.com",
			"type" : "free"
		},
				{
			"id" : "JqKvymryNaCjjKrAR",
			"type" : "free"
		},
	],
}

I want to update a specific array element’s email with custom generated id using Meteor query something like the below.

for instance, I want to update the document
if 'users.id' == "b1@gmail.com" then update it to users.id = 'SomeIDXXX'

So updated document should looks like below.

{
	"_id" : "zFndWBZTvZPgSKXHP",
	"activityId" : "aRDABihAYFoAW7jbC",
	"activityTitle" : "Test Mongo Document",
	"users" : [
		{
			"id" : "SomeIDXXX",
			"type" : "free"
		},
		{
			"id" : "JqKvymryNaCjjKrAR",
			"type" : "free"
		},

	],
}

I have tried the below but didnt work.

 Divisions.update(
      { activityId: activityId, "users.id": emailId },
      { $set: { "users": { id: _id } } }
    );

Can someone help me with the relevant Meteor query ? Thanks !

await Divisions.rawCollection().update(
  { activityId: activityId, "users.id": emailId },
  { $set: { "users.$[elem].id": id } },
  { arrayFilters: [ { "elem.id": emailId } ] }
);

2 Likes

Do you know the index of the item in array?

If so, you could do something like this:

 Divisions.update({ 
    activityId: activityId, 
    users: {
      $elemMatch: {
        id: emailId
      }
    }
  },    
  { 
    $set: { 
      "users.DESIRED_INDEX.id": _id
    } 
  }
);

If you don’t know the index, you could use this syntax.

1 Like