0

I want to update an inner element state field in a mongodb collection, I have given below the collection and my mongodb update statement.

    {
        "_id" : ObjectId("561b4c83e3603fcd1badaeb3"),
        "continent" : "Asia",
        "countries" : [
            {
                "country" : "India",
                "_id" : ObjectId("561b83c3626fca4a23c0131f"),
                "states" : [
                    {
                        "state" : "Kerala"
                    }
                 ........ many other states
                ]
            }
        ],
        "__v" : 0
    }

I used this mongodb query.

    db.places.update({ "_id" : ObjectId("561b4c83e3603fcd1badaeb3"), "countries.states.state": "Kerala" },{ $set: { "country.$.states.$.state": "Tamilnad" } } );

Expected result

    {
        "_id" : ObjectId("561b4c83e3603fcd1badaeb3"),
        "continent" : "Asia",
        "countries" : [
            {
                "country" : "India",
                "_id" : ObjectId("561b83c3626fca4a23c0131f"),
                "states" : [
                    {
                        "state" : "Goa"
                    }
                 ........ many other states
                ]
            }
        ],
        "__v" : 0
    }

Please help me.

1

2 Answers 2

0

You can try to use $addToSet to add an element in array

db.collection.update({ "_id" : ObjectId("561b4c83e3603fcd1badaeb3"), "countries.states.state": "Kerala" },{ $addToSet: { "countries.$.states": {"state":"Goa"} } } )

Hope it will help

Sign up to request clarification or add additional context in comments.

Comments

0

Mongo doesn't support multiple positional operators. You'll have to do it with js using mongo's foreach method

db.coll.find().forEach(function( doc ) {
  //supposing only one country will match the query 
    var statesCount = doc.countries[0].states.length;
    for(var i=0; i<statesCount; i++){
        if(doc.countries[0].states[i].state == "Kerala"){
            doc.countries[0].states[i].state = "Goa";
        }       
    }
    db.coll.save(doc);
});

Another option: This feature should be fixed in version 3.5.12, see here

hope this will help someone.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.