Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo - Update elements in nested array [duplicate]

I've a document that looks like

{
  _id: "123xyz",
  profile: {
    emails: [
      {
        "address" : "[email protected]",
        "primary" : true
      },
      {
        "address" : "[email protected]",
        "primary" : false
      }
    ]
  }
}

When a user set an email address as primary, and if he already has other emails, I want to set those other emails as non primary ie I'd like to give all the emails different from the new primary one the flag primary: false. According to some other SO answers like this one, this should work:

db.users.update(
  { _id: userId, 'profile.emails.address': { $ne: newEmailAddress } },
  { $set: { 'profile.emails.$.primary': false } }
);

But it fails with The positional operator did not find the match needed from the query. Unexpanded update: profile.emails.$.primary

The original document currently has just one email that differs from newEmailAddress.

like image 589
Guig Avatar asked Sep 12 '25 04:09

Guig


1 Answers

Here I found an answer to your question: Update an item in an array that is in an array

And with that solution in this case (with your structure):

db.mail.update({"profile.emails": {$elemMatch: {"address": 
{$ne: "[email protected]" }}}}, {$set: {"profile.emails.$.primary": "false"}})
like image 136
tretom Avatar answered Sep 13 '25 20:09

tretom