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

huangapple go评论80阅读模式
英文:

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

问题

假设我有以下代码:

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

有没有办法在不知道数据结构的情况下进行insertOne操作?但是在插入之前我必须更改_id

英文:

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.

答案1

得分: 0

在MongoDB中,ID字段始终为_id,因此您可以简单地执行以下操作:

result["_id"] = ... // 分配新的ID值

另请注意,bson.M是一个映射,因此不保留顺序。您可以仅更改ID并插入克隆,但字段顺序可能会改变。这通常不是一个问题。

如果顺序也很重要,请改用bson.D而不是bson.M,它保留顺序,但查找_id会更复杂:您必须使用循环,因为bson.D不是映射而是切片。

使用bson.D时,代码可能如下所示:

var result bson.D
// 查询...

// 更改ID:
for i := range result {
    if result[i].Key == "_id" {
        result[i].Value = ... // 新的ID值
        break
    }
}

// 现在您可以插入result
英文:

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

huangapple
  • 本文由 发表于 2022年10月5日 11:23:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/73955636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定