英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论