gpt4 book ai didi

mongodb - UpdateOne、ReplaceOne、FindOneAndReplace - 模式匹配,但没有更新数据

转载 作者:数据小太阳 更新时间:2023-10-29 03:19:01 27 4
gpt4 key购买 nike

我正在使用 Mongo Go 适配器:github.com/mongodb/mongo-go-driver/

我正在尝试不同的模式,但没有一个适合我。

//引用结构

type userbase struct {
Name string `bosn:"Name"`
Coins int `bson:"Coins"`
}

//引用代码,更新_id,但不更新值

filter := bson.M{"name": "Dinamis"}
update := bson.D{{"$inc", bson.M{"Coins": 1}}}
db := Client.Database("Nothing").Collection("dataUser")
db.UpdateOne(context.Background(), filter, update)

//更新我也用过的过滤器

update := bson.D{{"$inc", bson.D{{"Coins", 1},}},}

//也尝试了简单的方法

update := &userbase{name, amount} //should i try *userbase{} ?

//我也试过了

ReplaceOne() 
FindOneAndReplace()
FindOneAndUpdate()

很难深入挖掘 b-cuz 实际文档的运气:https://docs.mongodb.com/ecosystem/drivers/go/

最佳答案

感谢@Wan Bachtiar 在官方 MongoDB-go-adapter 组中回答这个问题。

By default queries in MongoDB is case sensitive on the field name. In your struct you defined the field to be Name, but in your filter to specify name. This would result in no documents matching the query predicates for the the update operation. For example, if you have a document as below:

{ "_id": ObjectId("..."), "Name": "Dinamis", "Coins": 1 }

You can perform an update to increment the number of Coins using below snippet:

collection := client.Database("Nothing").Collection("dataUser")
filter := bson.M{"Name": "Dinamis"}
update := bson.D{{"$inc", bson.M{"Coins": 1}}}
result, err := collection.UpdateOne(context.TODO(), filter, update)

Also, note that you have a typo on the bson tag in your struct. It’s supposed to be bson:"Name" not bosn:"Name". You may find Query Documents as a useful reference (Select the Go tab to show examples in Go)

Regards, Wan.

关于mongodb - UpdateOne、ReplaceOne、FindOneAndReplace - 模式匹配,但没有更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56875529/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com