繁体   English   中英

通过mgo v2更新结构的数组元素(golang,mongoDB)

[英]update an array element of a struct by mgo v2 (golang,mongoDB)

我的结构如下:

type Meet struct {
    Title   string    `json:title`
    Time    time.Time `json:time`
    Host    string    `json:host`
    Crowd   []string  `json:crowd`
    Geo     Location  `json:location`
    Invoice []Bill    `json:invoice`
}

type User struct {
    ID         bson.ObjectId   `json:"id" bson:"_id,omitempty"`
    Name       string          `json:name`
    Phone      string          `json:phone`
    Email      string          `json:email`
    Vc         string          `json:vc`
    Status     int8            `json:status`
    Avatar     string          `json:avatar`
    FriendList []bson.ObjectId `json:friendlist`
    Meetings   []Meet          `json:meetings`
    Requests   []Request       `json:request`
}

并希望更新Meet的发票(如:User.Meetings [0] .Invoice)我的代码如下:

        query := bson.M{
            "_id":            bson.ObjectIdHex(personId),
            "Meetings.Title": Title,
            "Meetings.Geo":   Geo,
        }
        update := bson.M{
            "$set": bson.M{
                "Meetings.$.Invoice": updateInvoice,
            },
        }

        updateErr = collection.Update(query, update)

我得到的只是没有找到error.commenting Meetings.Geo没有帮助,并导致相同的原因。找不到。 这是我的查询错误或什么?

查询中的字段应为meetings.title和meetings.geo。 我刚刚用我的一个DB测试了它,并且这些字段很重要。 在您的更新中,会议应该是会议。 名称取自结构项标记名称而不是结构项目名称。 例如

struct test {
    ID bson.   bson.ObjectId `bson:"_id"`
    TestString string        `bson:"ts"`
    Amount     int           `bson:"am"`
}

query := bson.M{"ts": "test", "am": 2}

由于_id字段必须存在,因此不能对_id进行omitempty。

暂无
暂无

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

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