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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于ucc28019的pfc电路中芯片一直不工作
  • ¥15 yolov8在3588板子端c++推理报错
  • ¥50 unitywebrequest分段下载导致报错,如何解决?
  • ¥15 错误使用 gretna_GUI_PreprocessInterface>RunBtn_Callback
  • ¥15 WPF如何用Chart绘画出Y轴的左边数据
  • ¥15 pycharm无法查看内置代码
  • ¥15 跑hls xfopencv的例程standalone_hls_axi_example出的错误,csim没问题,c synthesis出的错误
  • ¥15 sqlserver update语句逐行生效
  • ¥20 Windows10系统命令行调用
  • ¥15 php环境如何实现国密SM2相关功能