How to update a subdocument in mongodb

2019-02-28 23:21发布

问题:

I know the question have been asked many times, but I can't figure out how to update a subdocument in mongo.

Here's my Schema:

// Schemas
var ContactSchema = new mongoose.Schema({
  first: String,
  last: String,
  mobile: String,
  home: String,
  office: String,
  email: String,
  company: String,
  description: String,
  keywords: []
});

var UserSchema = new mongoose.Schema({
  email: {
      type: String,
      unique: true,
      required: true
  },
  password: {
      type: String,
      required: true
  },
  contacts: [ContactSchema]
});

My collection looks like this:

db.users.find({}).pretty()
{
    "_id" : ObjectId("5500b5b8908520754a8c2420"),
    "email" : "test@random.org",
    "password" :     "$2a$08$iqSTgtW27TLeBSUkqIV1SeyMyXlnbj/qavRWhIKn3O2qfHOybN9uu",
    "__v" : 8,
    "contacts" : [
        {
            "first" : "Jessica",
            "last" : "Vento",
            "_id" : ObjectId("550199b1fe544adf50bc291d"),
            "keywords" : [ ]
        },
        {
            "first" : "Tintin",
            "last" : "Milou",
            "_id" : ObjectId("550199c6fe544adf50bc291e"),
            "keywords" : [ ]
        }
    ]
}

Say I want to update subdocument of id 550199c6fe544adf50bc291e by doing:

db.users.update({_id: ObjectId("5500b5b8908520754a8c2420"), "contacts._id": ObjectId("550199c6fe544adf50bc291e")}, myNewDocument)

with myNewDocument like:

{ "_id" : ObjectId("550199b1fe544adf50bc291d"), "first" : "test" }

It returns an error:

db.users.update({_id: ObjectId("5500b5b8908520754a8c2420"), "contacts._id":     ObjectId("550199c6fe544adf50bc291e")}, myNewdocument)
WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 16837,
        "errmsg" : "The _id field cannot be changed from {_id:     ObjectId('5500b5b8908520754a8c2420')} to {_id:     ObjectId('550199b1fe544adf50bc291d')}."
    }
})

I understand that mongo tries to replace the parent document and not the subdocument, but in the end, I don't know how to update my subdocument.

回答1:

You need to use the $ operator to update a subdocument in an array

Using contacts.$ will point mongoDB to update the relevant subdocument.

db.users.update({_id: ObjectId("5500b5b8908520754a8c2420"), 
  "contacts._id": ObjectId("550199c6fe544adf50bc291e")}, 
 {"$set":{"contacts.$":myNewDocument}})

I am not sure why you are changing the _id of the subdocument. That is not advisable.

If you want to change a particular field of the subdocument use the contacts.$.<field_name> to update the particular field of the subdocument.