首页 > 解决方案 > 在文档 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) 但仍然找不到有效的工作方式。一点帮助将不胜感激。谢谢大家。

标签: mongodbgoaggregation-frameworkmgo

解决方案


这是一个简单的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"

推荐阅读