繁体   English   中英

无法从Mongo记录[mgo]:golang在结构接口上仅向上插入一个值

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

基本上我想通过给定完全结构接口作为collection.Upsert(selector,change)中的更改参数来更新mongodb文档中的一个值。 我们如何做到这一点而又不会失去其他价值观。 其他(type,category.rerportby,createon,info)值应保留在现有值上,仅将工厂位置值更新为PLANT07BAR

注意:我要完全使用服务通知结构对象来执行此操作。

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)

}

我想通过给mongo Upsert函数提供完整的struct接口来更新工厂和位置。 因为我想动态决定应该更新什么。 但是当我更新工厂和位置时,其他值将变为LOST 在mongo记录中。

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)

这将仅更新提供的字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM