Search code examples
mongodbmongodb-shell

Update child element on mongodb


I've got a little problem with mongodb update method. This is my (simplified) schemas:

{
   profile: {
      birthdate: "XXX",
      city: "xxx"
   },
   account: {
      username: "...",
      password: "....",
      visits: 0
   }
}

I've got 2000 objects in DB. I want to anonymize datas by removing username values.

I tried this:

db.users.update({}, {$set: account: {username: ""}}, false, true);

That doesn't works, this query remove password field and visits. I understand why, but how to do ?

db.users.update({}, {account: { $set: {username: ""}}}, false, true);

mongo want to assign "$set" field, so that dosen't work.

My question is: how to update descendant fields without removing the entire "account" subdocument ?

(Setting "upsert" to true does the same.)


Solution

  • You should use:

    $set:{"account.username":""}
    

    Just wondering why you don't use $unset?