如何表示包含不同类型的数组

huangapple go评论93阅读模式
英文:

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}

huangapple
  • 本文由 发表于 2013年9月27日 23:50:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/19055037.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定