mongodb - 在文档 mongodb mgo 驱动程序中增加嵌套数组的特定值
问题描述
这是我在 json 中的 mongo 集合:
"messages" :
{
"_id" : ObjectId("5c26844696b72e4b6c9ceee7"),
"pointer" : ObjectId("5c26844696b72e4b6c9ceee6"),
"messages" : [
{
"uuid" : "f03f7977-0b4e-11e9-9f95-144fd7c03810",
"content" : "Hello",
"reportedTimes":0
},
{
"uuid" : "78bb831d-0b57-11e9-a286-144fd7c03810",
"content" : "Yes",
"reportedTimes":0
}
]
}
我想从“指针”和“uuid”更新“reportedTimes”值。我尝试了许多聚合,但没有这样的结果:
pipe := []bson.M{bson.M{"$match": bson.M{"pointer": knownPointer}}, {"messages": bson.M{"$match": bson.M{"uuid": knownUUID}}}, {"$inc": bson.M{"messages.$.reportedTimes": 1}}}
那个返回我不能使用“$inc”
或者那个
pipe := []bson.M{{"$match": bson.M{"pointer": knownPointer}}, {"$unwind": "$messages"}, {"$project": bson.M{"uuid": "$messages.uuid", "reportedTimes": "$messages.reportedTimes"}}, {"$match": bson.M{"uuid": knownUuid}}} then inc.
我什至没有找到我所有的尝试查询......我完全被卡住了......我也尝试过 Update(selector, query) 但仍然找不到有效的工作方式。一点帮助将不胜感激。谢谢大家。
解决方案
这是一个简单的Collection.Update()
操作,无需为此使用聚合:
err := c.Update(bson.M{
"pointer": knownPointer,
"messages.uuid": knownUUID,
}, bson.M{
"$inc": bson.M{
"messages.$.reportedTimes": 1,
},
})
以下是如何设置参数以增加reportedTimes
文档的第一条消息:
knownPointer := bson.ObjectIdHex("5c26844696b72e4b6c9ceee6")
knownUUID := "f03f7977-0b4e-11e9-9f95-144fd7c03810"
推荐阅读
- reactjs - 尝试从已部署的 create-react-app 中的公用文件夹中获取 json 文件时出现 404 错误
- python - Python。多处理
- laravel - Laravel 设置单元格边框样式
- r - 在 R 中查找多个模式的列表中元素的位置
- python - 在 OpenMaya 中获取顶点法线?
- android - 我怎样才能获得像 ColorOs、Flyme、LineageOS 等 Android 类型?
- react-native - 反应原生 | 钩子组件
- python - 如何基于单列将数据框着色为在整行中具有相同颜色的条件热图
- android - 使用 OnBackPressedDispatcher() 的 OnBackPressedCallback() 不起作用
- python - 从 Pandas 数据透视表框架中注释数据点