0

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

2 Answers 2

1

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})

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

Comments

1

Try using $exists and $unset:

query:= bson.M{"$exists":bson.M{"field2.key1":true}}
replace:=bson.M{"$unset":bson.M{"field2.key1":""}}
collection.UpdateAll(query,replace)

This should find all documents containing field2.key1, and remove that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.