4

I've a document that looks like

{
  _id: "123xyz",
  profile: {
    emails: [
      {
        "address" : "foo@gmail.com",
        "primary" : true
      },
      {
        "address" : "bar@gmail.com",
        "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.

Community
  • 1
  • 1
Guig
  • 9,891
  • 7
  • 64
  • 126

1 Answers1

3

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: "new@gmail.com" }}}}, {$set: {"profile.emails.$.primary": "false"}})
Community
  • 1
  • 1
tretom
  • 559
  • 1
  • 7
  • 17