0

I have a Meteor Mongo document as shown below

{
    "_id" : "zFndWBZTvZPgSKXHP",
    "activityId" : "aRDABihAYFoAW7jbC",
    "activityTitle" : "Test Mongo Document",
    "users" : [
        {
            "id" : "[email protected]",
            "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' == "[email protected]" 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 !

3 Answers 3

1

Your query is actually almost right except for a small part where we want to identify the element to be updated by its index.

Divisions.update({
"activityId": "aRDABihAYFoAW7jbC",
 "users.id": "[email protected]"
}, {
$set: {"users.$.id": "[email protected]"}
})
Sign up to request clarification or add additional context in comments.

Comments

1

You might need the arrayFilters option.

Divisions.update(
  { activityId: activityId },
  { $set: { "users.$[elem].id": "SomeIDXXX" } },
  { arrayFilters: [ { "elem.id": "[email protected]" } ], multi: true }
);

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/

Comments

0

You need to use the $push operator instead of $set.

{ $push: { <field1>: <value1>, ... } }

2 Comments

This adds a new object to the array. Syam is asking how to update an existing object in the array.
Yes @BartS said is right. I want to update existing element.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.