英文:
How to represent an array with mixed types
问题
我正在构建一个使用MongoDB的聚合管道查询,其中包含$substr
命令,但我不知道如何在Go中使用mgo驱动程序表示它所需的数组,因为它包含不同类型的值(字符串、整数)。
以下是JavaScript中的查询示例:
[{$group: {"_id": {"dt": {"$substr": ["$dt", 0, 6]}}}}]
这个查询的目的是从聚合的前一个阶段获取dt
字段的子字符串,起始索引为0,结束索引为6。
在Go中,你尝试了以下代码:
[]bson.M{"$group": bson.M{"_id": bson.M{"dt": bson.M{"$substr": ["$dt", 0, 6]}}}}
但是["$dt", 0, 6]
不是正确的表示方式,而且你尝试的所有方法似乎都失败了。
英文:
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.
答案1
得分: 14
你可以使用类型为[]interface{}
的切片来表示这些值:
l := []interface{}{"$dt", 0, 6}
如果你觉得语法有点混乱,你可以很容易地定义一个本地类型,使其看起来更好看:
type list []interface{}
l := list{"$dt", 0, 6}
英文:
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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论