mongodb - 通过 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)
我得到的只是没有找到错误。评论会议。地理没有帮助并导致同样的原因。没有找到。这是我的查询有问题还是什么?
解决方案
查询中的字段应该是 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 字段必须存在。
推荐阅读
- firebase - 使用内部数据的 Firebase 身份验证规则
- reactjs - React Native - ReactNavigation.addNavigationHelpers 不是一个函数
- javascript - 从JS中的字符串中删除所有特殊字符
- java - Servlet 实例是线程还是进程?
- scala - 在Scala中访问嵌套If else块之外的ArrayList
- matlab - 并行化 MATLAB 代码
- node.js - Node.js 路由在 Microsoft Azure 上不起作用
- laravel-5.4 - 在 Laravel 5.4 中使用 Auth 使用 or 条件登录
- highcharts - 如何在单行中显示标签上的文本
- java - HashMap Java 中布尔值的组合