Search code examples
mongodbgomgo

How to represent an array with mixed types


I am constructing an aggregation pipeline query with the $substr command from MongoDB but I don't know how to represent the array it requires in Go with the mgo driver because it contains different types of values (string, int).

Here is the query in javascript:

[ {$group: {"_id": {"dt": {"$substr": ["$dt",0,6]}}}} ]

What this is trying to do is get the substring of dt (from the previous stage of aggregation) with starting index 0 and ending index 6.

In Go i got:

[]bson.M{"$group": bson.M{"_id": bson.M{"dt": bson.M{"$substr": ["$dt",0,6]}}}}}

but ["$dt",0,6] is not a correct representation and everything I tried seems to fail.


Solution

  • You can represent these values using a slice of type []interface{}:

        l := []interface{}{"$dt", 0, 6}
    

    If you find the syntax a little dirty, you can easily define a local type to make it look nicer:

        type list []interface{}
        l := list{"$dt", 0, 6}