Search code examples
mongodbgoaggregation-frameworkmgo

increment specific value on nested array in document mongodb mgo driver


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.


Solution

  • 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"