Clicky

Mongo - Update element inside array

July 18, 2016

 Problem:

Update seller.id,  from 1 to 4, inside the offers array:

{
    “_id” : ObjectId(“578c7e3c92022220f068d8dd”),
    (…)
    “offers” : { 
        (…)
        “offers” : [
            {
                “productId” : “20001534”,
                (…)
                “seller” : {
                    “_id” : “1”,
                    “name” : “Mediamarkt”
                },
            }
        ]
    }
}

Solution:

db.getCollection(<target_collection_name>).update({“offers.offers.seller._id”:“1”},{$set:{“offers.offers.$.seller._id”:“4”}}, false, true)

  • The third parameters tells mongo not to create new documents when no math es are found.
  • The fourth parameters tells mongo to updated all matching documents