Golang aggregation group by multiple values with MongoDB

I'm trying to aggregate with the group operator and multiples values
I made this query in MongoDB :

db.Modules.aggregate([{$group: {_id: {"module":"$module","host":"$host"},"status":{$last:"$status"}}}])

I use package : go.mongodb.org
I want to implement it in my code in Golang with :

group := bson.D{{"$group", bson.D{{"_id", bson.D{{"module", "$module", "host", "$host"}}}, {"time", bson.D{{"$last","$time"}}}, {"level", bson.D{{"$last","$level"}}}}}}

cursor, err := collection.Aggregate(ctx, mongo.Pipeline{group})
if err != nil {
    fmt.Println("Failed to Aggregate: ", err)
}
defer cursor.Close(ctx)
if err = cursor.All(ctx, &results); err != nil {
    fmt.Printf("cursor.All() error:", err)
}

When I want to compile my code it returns the following error:

too many values in primitive.E{...}

Can anyone tell me where the error in my group. Thank you for your help !

1 answer

  • answered 2021-05-05 10:36 icza

    The problem is with this fragment, with this composite literal:

    bson.D{{"module", "$module", "host", "$host"}}
    

    bson.D is a slice of fields, where fields are key-value pairs (that is: 2 elements), and you try to define an element (a field) with 4 values.

    It should be:

    bson.D{{"module", "$module"}, {"host", "$host"}}
    

    In general you should format these expressions to multiple lines. Easier to read, easier to understand, easier to modify.

    For example:

    group := bson.D{
        {
            "$group", bson.D{
                {
                    "_id", bson.D{
                        {"module", "$module"},
                        {"host", "$host"},
                    },
                },
                {"time", bson.D{{"$last", "$time"}}},
                {"level", bson.D{{"$last", "$level"}}},
            },
        },
    }