Search code examples
mongodbgomgo

updating mongo documents based in map value and remove that value


am currently working in Go and have a mongo database (connected via gopkg.in/mgo.v2) so, right now I have a data structure similar to:

{
    "_id" : "some_id_bson",
    "field1" : "value1",
    "field2" : {
      {
      "key1" : "v1",
      "key2" : "v2",
      "key3" : "v3",
      "key4" : "v4"
      }
    }
}

So, basically what I need to do (as an example) is to update in the database all the records that contains key1 and remove that from the json, so the result would be something like:

{
        "_id" : "some_id_bson",
        "field1" : "value1",
        "field2" : {
          {
          "key2" : "v2",
          "key3" : "v3",
          "key4" : "v4"
          }
        }
    }

What can I use to achieve this? I have been searching and cannot find something oriented to maps (field2 is a map). Thanks in advance


Solution

  • It seems like you're asking how to remove a property from a nested object in a particular document, which appears as if to be answered here: How to remove property of nested object from MongoDB document?. from the main answer there:

    Use $unset as below :

    db.collectionName.update({},{"$unset":{"values.727920":""}}) EDIT For updating multiple documents use update options like :

    db.collectionName.update({},{"$unset":{"values.727920":""}},{"multi":true})