j3d
j3d

Reputation: 9724

MongoDB: How to update a compound item of an array ensuring no duplicates

Here below is a hypothetical Users collection where more than one address is allowed:

{
  "firstName": "Joe",
  "lastName": "Grey",
  ...
  "addresses":
  [
    {
      "name": "Default",
      "street": "..."
      ...
    },
    {
      "name": "Home",
      "street": "..."
      ...
    },
    {
      "name": "Office",
      "street": "..."
      ...
    }
  ]
}

Every address has a name... which should be unique – e.g. there couldn't be two addresses named Default. If I want to update let's say the address at index 1 (Home), how do I ensure the update data does not contain names Default and Office?

I guess a two-steps approach (i.e. find and then update) wouldn't be very correct since data might be updated between the find and the subsequent update operation, isn't?

Upvotes: 0

Views: 44

Answers (1)

Will Shaver
Will Shaver

Reputation: 13079

var renamed = 'Office'; // from user input
var users = getUserMongoCollection();    

users.update({_id:userId, 'addresses.name': { $ne : renamed } },
    { $set : { 'addresses.1.name' : renamed } }, function(err){
        //all done!
    });

Find the record by ID, and only update it if the array doesn't contain the new name.

Upvotes: 1

Related Questions