Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way that can find one document and clone it with changing id/value in mongodb with Go

suppose I have code like this:

        var result bson.M
        err := coll.FindOne(context.TODO(), filter).Decode(&result)
        if err != nil {
            panic(err)
        }
        // somehow I can change the _id before I do insertOne
        if _, err := coll.InsertOne(context.TODO(), result); err != nil {
            panic(err)
        }

is there a way I can insertOne without knowing the data struct? But I have to change the _id before I insert it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The ID field in MongoDB is always _id, so you may simply do:

result["_id"] = ... // Assign new ID value

Also please note that bson.M is a map, and as such does not retain order. You may simply change only the ID and insert the clone, but field order may change. This usually isn’t a problem.

If order is also important, use bson.D instead of bson.M which retains order, but finding the _id is a little more complex: you have to use a loop as bson.D is not a map but a slice.

This is how it could look like when using bson.D:

var result bson.D
// Query...

// Change ID:
for i := range result {
    if result[i].Key == "_id" {
        result[i].Value = ... // new id value
        break
    }
}

// Now you can insert result
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading