0
votes

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
Can you show us the document you get when you query db.institutions.findOne({ "_id": ObjectId("57f25706762c06cb7d9422fc") })?chridam
@chridam My find query is db.institutions.find({ "campus.country" : "SS1", "_id" : ObjectId("57f26824762c06cb7d982e37") }, { "campus": true }); { "_id" : ObjectId("57f26824762c06cb7d982e37"), "campus" : [ { "_id" : ObjectId("578500ee87e4c326183e5201"), "country" : "GB", "coreId" : NumberInt(14677), "city" : "Norwich" } ] }Shahbaz
But that's totally different from the query in your update where you are querying for a document with { "_id": ObjectId("57f25706762c06cb7d9422fc") }chridam
It changed when Db is imported again, there is no problem of id dearShahbaz

1 Answers

3
votes

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"