How to represent an array with mixed types

2020-08-21 02:00发布

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.

标签: mongodb go mgo
1条回答
家丑人穷心不美
2楼-- · 2020-08-21 02:28

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}
查看更多
登录 后发表回答