dousha2020 2018-12-29 22:16
浏览 69
已采纳

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

Here is my mongo collection in json :

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

I would like to update the "reportedTimes" value from a "pointer" and a "uuid". I tried many aggregations but without result like that one :

pipe := []bson.M{bson.M{"$match": bson.M{"pointer": knownPointer}}, {"messages": bson.M{"$match": bson.M{"uuid": knownUUID}}}, {"$inc": bson.M{"messages.$.reportedTimes": 1}}}

That one returns that I cannot use "$inc"

or that one

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.

I even don't find all my attempts queries... I'm completely stuck... I also tried with Update(selector, query) but still cannot find the working and efficient way to do it. A little help would be appreciated. Thanks all.

  • 写回答

1条回答 默认 最新

  • dsyrdwdbo47282676 2018-12-29 22:33
    关注

    This is a simple Collection.Update() operation, no need to use aggregation for this:

    err := c.Update(bson.M{
        "pointer":       knownPointer,
        "messages.uuid": knownUUID,
    }, bson.M{
        "$inc": bson.M{
            "messages.$.reportedTimes": 1,
        },
    })
    

    Here's how to set the parameters to increment the reportedTimes of the first message of your document:

    knownPointer := bson.ObjectIdHex("5c26844696b72e4b6c9ceee6")
    knownUUID := "f03f7977-0b4e-11e9-9f95-144fd7c03810"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大