如何用混合类型表示一个数组 [英] How to represent an array with mixed types

查看:121
本文介绍了如何用混合类型表示一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用MongoDB中的 $ substr 命令构建一个聚合管道查询,但我不知道如何使用mgo驱动程序在Go中表示它需要的数组,因为它包含不同类型的值(string,int)。



以下是javascript中的查询:

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

这个试图做的是得到 dt 的子字符串

在Go中,我得到了:

<$ p $ b。{$ group:bson.M {_id:bson.M {dt:bson.M {$ substr:[$ dt ,0,6]}}}}}

[$ dt ,0,6] 不是正确的表示形式,我尝试的所有内容似乎都失败了。

解决方案

您可以使用 [] interface {} 类型的片段来表示这些值:

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

语法有点脏,你可以很容易地定义一个本地类型,使它看起来更好:

  type list [] interface {} 
l:= list {$ 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.

解决方案

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}

这篇关于如何用混合类型表示一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆