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

Time:10-05

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.

CodePudding user response:

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
  • Related