mongoDB updateOne not updating a record

2019-07-24 20:46发布

问题:

I am trying to update a record in mongoDB using updateOne, the un updating record is in array, and all fields are updating except one field which is country, I have tried to update it using MongoChef (a GUI of MongoDB for linux), but it doesn't work, also If I update one the Document using Edit in GUI then that record is ready to update after that.

I have tried with the following query in MongoChef

db.institutions.updateOne({
    "campus": { "$elemMatch": { "_id": ObjectId("578500ef87e4c326183e520e")} },
    "_id": ObjectId("57f25706762c06cb7d9422fc") 
    },
    {
    "$set" : { "campus.$.country" : "SS1"
    }
});

Only country field is not updating If I update any other field it works fine.

The document structure is listed under

{ 
    "_id" : ObjectId("57f26824762c06cb7d982e37"), 
    "campus" : [
        {
            "_id" : ObjectId("578500ee87e4c326183e5201"), 
            "country" : "GB", 
            "coreId" : NumberInt(1), 
            "city" : "Norwich", 
        }
    ]
}

Thanks in advance any help is appreciatiable

回答1:

try this query

db.institutions.updateOne(
    {
      "campus._id": ObjectId("578500ef87e4c326183e520e"),
      "_id": ObjectId("57f25706762c06cb7d9422fc") 
    },
    {
      "$set" : { "campus.$.country" : "SS1"}
    }
);

N.B: if use mongodb driver or mongoose then no need to use ObjectId("") just use "578500ef87e4c326183e520e"