首页 > 解决方案 > 通过 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`
}

并想更新会议发票(例如: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)

我得到的只是没有找到错误。评论会议。地理没有帮助并导致同样的原因。没有找到。这是我的查询有问题还是什么?

标签: mongodbgostructmgo

解决方案


查询中的字段应该是 meeting.title 和 meeting.geo。我刚刚用我的一个数据库对其进行了测试,并且字段的情况很重要。在您的更新中,会议应该是会议。名称取自结构项目标签名称,而不是结构项目名称。例如

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 字段必须存在。


推荐阅读