我的mongo数据库中有类似于此文档的文档。
{
"_id": ObjectId("5cbf416ec6490b9baff4d284"),
"rewards" : [
{
"percent" : NumberLong(100),
"promotion_id" : "promotest"
}
],
"eligible_for": ["XYZ","ABC"]
}当我使用适当的文档进行更新时,它就会正确地更新文档
但当我传递奖励时,eligible_for as null,然后eligible_for更新为null,但奖励未更新为null
{
"rewards" : null,
"eligible_for": null
}则新更新的文档
{
"_id": ObjectId("5cbf416ec6490b9baff4d284"),
"rewards" : [
{
"percent" : NumberLong(100),
"promotion_id" : "promotest"
}
],
"eligible_for": null
}这是我使用mongo-go-driver更新文档所使用的查询。r.PollingGameCollection.UpdateOne(ctx, bson.M{"_id": poll.RawId}, M{"$set": poll})
对象包括:
type PollingGame struct {
RawId *objectid.ObjectID `json:"-" bson:"_id,omitempty"`
Rewards *[]Reward `json:"rewards,omitempty" bson:"rewards,omitempty"`
EligibleFor []string `json:"eligible_for,omitempty" bson:"eligible_for, omitempty"`
}type Reward struct {
Percent int `json:"percent,omitempty" bson:"percent,omitempty"`
PromotionId string `json:"promotion_id,omitempty" bson:"promotion_id,omitempty"`
}发布于 2019-10-11 19:57:14
首先:在PollingGame.EligibleForbson"的bson标记值中有一个额外的空格,删除它:bson:"eligible_for, omitempty"。
如果删除该空格,您会注意到它甚至不再将eligible_for设置为null。
原因是您使用了,omitempty选项。这将告诉驱动程序,如果该字段的值为nil (零值),则排除该字段。所以您想要更新,但是这些字段不会包含在$set操作中,所以它们不会更改。
如果删除,omitempty选项,它将起作用:
type PollingGame struct {
RawId *primitive.ObjectID `json:"-" bson:"_id,omitempty"`
Rewards *[]Reward `json:"rewards,omitempty" bson:"rewards"`
EligibleFor []string `json:"eligible_for,omitempty" bson:"eligible_for"`
}(注意,我还将objectid.ObjectID更改为primitive.ObjectID,因为这是您必须用于MongoDB对象ID的类型。)
https://stackoverflow.com/questions/58340098
复制相似问题