在文档 mongodb mgo 驱动程序中增加嵌套数组的特定值

increment specific value on nested array in document mongodb mgo driver

这是我在 json 中的 mongo collection :

"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
   }
  ]
}

我想更新 "pointer" 和 "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}}}

那个 returns 我不能使用“$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"