go mongo 驱动程序更新无法将对象数组设置为空

Sri*_*vas 4 go mongodb mongo-go

我的 mongo db 中有与此文档类似的文档

{
    "_id": ObjectId("5cbf416ec6490b9baff4d284"),
    "rewards" : [ 
        {
            "percent" : NumberLong(100),
            "promotion_id" : "promotest"
        }
    ],
    "eligible_for": ["XYZ","ABC"]

}
Run Code Online (Sandbox Code Playgroud)

当我用正确的文档更新时,它正在正确更新文档

但是当我通过奖励时,qualified_for 为 null,然后qualified_for 更新为 null 但奖励未更新为 null

{
    "rewards" : null,
    "eligible_for": null

}
Run Code Online (Sandbox Code Playgroud)

然后是新更新的文档

{
    "_id": ObjectId("5cbf416ec6490b9baff4d284"),
    "rewards" : [ 
        {
            "percent" : NumberLong(100),
            "promotion_id" : "promotest"
        }
    ],
    "eligible_for": null

}
Run Code Online (Sandbox Code Playgroud)

这是我用来使用 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"`

}
Run Code Online (Sandbox Code Playgroud)
type Reward struct {
    Percent     int    `json:"percent,omitempty" bson:"percent,omitempty"`
    PromotionId string `json:"promotion_id,omitempty" bson:"promotion_id,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)

icz*_*cza 5

首先:您在 的bson标签值中有一个额外的空格PollingGame.EligibleForbson",请删除:bson:"eligible_for, omitempty"

如果您删除该空间,您会注意到它甚至不再设置eligible_fornull

原因是因为您使用了该,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"`
}
Run Code Online (Sandbox Code Playgroud)

(注意我也更改objectid.ObjectIDprimitive.ObjectID因为这是您必须用于 MongoDB 对象 ID 的类型。)