无法从 Mongo 记录 [mgo]:golang 的结构接口上仅更新一个值

Cannot Upsert only one value on struct interface from Mongo record [mgo]:golang

基本上我想通过给定 fully 结构接口更新 mongodb 文档中的一个值作为 collection.Upsert 中的更改参数(选择器,更改)。我们如何在不将其他值丢失为空的情况下做到这一点。其他(类型,category.rerportby,createon,信息)值应保留在 现有值 上,仅更新 plant location 值转换为 PLANT07BAR)

NOTE: I want use completely Service Notification Struct Object for do this.

DatabaseName:WO 
CollectionName:SERVICE_NOTIFICATIONS

包款

//models.ServiceNotification
type ServiceNotification struct {
    NotificationNo string                `json:"notification_no" bson:"notification_no"`
    Type           string                `json:"type" bson:"type"`
    Category       string                `json:"category" bson:"category"`
        Plant          string                `json:"plant" bson:"plant"`
    Location         string              `json:"location" bson:"location"`
    ReportedBy     string                `json:"reportedby" bson:"reportedby"`
    Info           map[string]interface{}`json:"info" bson:"info"`
    SAPInfo        SAPNotificationInfo   `json:"sapinfo" bson:"sapinfo"`
        CreateOn       string                `json:"createon" bson:"createon"`
    UpdateOn       string                `json:"updateon" bson:"updateon"`
}

package main

func main(){

input := models.ServiceNotification{
    NotificationNo:000120,
    Plant:"Plant07",
    Location:"BAR",
}
Change_ServiceNotification(input)

}

I want update plant and location by given complete struct interface to the mongo Upsert function. because I want to decide dynamically what should update . But when I update plant and location other values going to be LOST. in mongo record.

func Change_ServiceNotification(notification models.ServiceNotification) error {
    session, err := commons.GetMongoSession()
    if err != nil {
        return errors.New("Cannot create mongodb session" + err.Error())
    }
    defer session.Close()
    var col = session.DB(WO).C(SERVICE_NOTIFICATIONS)

    selector := bson.M{"notification_no": notification.NotificationNo}

    _, err = col.Upsert(selector, notification)
    if err != nil {
        errMsg := "Cannot update service notification " + err.Error()
        return errors.New(errMsg)
    }
    return nil
}

感谢您的帮助

提前致谢

你不能这样做,但你可以使用 MongoDB 的 $set 运算符(跳过错误检查):

input := Bson.M{
    "$set": bson.M{
        "plant": "Plant07",
        // Further fields here...
    }
}
selector := bson.M{"notification_no": notification.NotificationNo}
col.Upsert(selector, input)

这将仅更新提供的字段。