一切正常,直到
go.mongodb.org/mongo-driver v1.4.0-rc0
但不会以
开头go.mongodb.org/mongo-driver v1.4.0
及以上。
自 v1.4.0 起 Collection.BulkWrite() 出现以下错误:
panic: update document must contain key beginning with '$'
这是处理插入/更新的方法:
func (db *DB) BulkUpsertDataModel(ctx context.Context, documents []*dbmodel.DataModel) error {
var models []mongo.WriteModel
for _, value := range documents {
if value.Id == primitive.NilObjectID {
models = append(models, mongo.NewInsertOneModel().SetDocument(value))
} else {
var updateModel = mongo.NewUpdateOneModel()
updateModel.SetFilter(bson.M{"_id": value.Id})
updateModel.SetUpdate(value)
models = append(models, updateModel)
}
}
_, err := db.Collection(Collection).BulkWrite(ctx, models)
return err
}
DataModel 的 id 是
Id primitive.ObjectID `json:"id" bson:"_id,omitempty"`
代码有什么问题?这对我来说真的很奇怪,因为它已经工作了很长时间。
答案 0 :(得分:0)
感谢您的帮助。 解决办法是
updateModel.SetUpdate(bson.D{
{"$set", value},
})