Search code examples
mongodbgomongo-go

Converting MongoDB $max result to golang data


I try to get max values from MongoDB collection from my Go code. What type should I use to decode result?

When I use bson.D{} as val2 type the result looks like [{_id <nil>} {max 66} {cnt 14}].

Here's the code:

    filter := []bson.M{{
        "$group": bson.M{
            "_id": nil,
            "max": bson.M{"$max": "$hellid"},
        }},
    }

    cursor, err := collection.Aggregate(ctx, filter)

    for cursor.Next(ctx) {
        val2 := ???
        err := cursor.Decode(&val2)
        fmt.Printf("cursor: %v, value: %v\n", cursor.Current, val2)
    }
}

Solution

  • Using bson.D already works as you presented. The problem may be you can't "easily" get out the max and cnt values.

    Model your result document with a struct like this:

    type result struct {
        Max   int `bson:"max"`
        Count int `bson:"cnt"
    }
    

    Although cnt is not produced by the example code you provided.

    And then:

    var res result
    err := cursor.Decode(&res)