Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent an array with mixed types

Tags:

mongodb

go

mgo

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.

like image 845
Makis Tsantekidis Avatar asked Sep 27 '13 15:09

Makis Tsantekidis


People also ask

How do you create a mixed array?

You can create JavaScript array with mixed data types as well, for example, array containing both numbers and strings: var MixArr = [1, “Mixed”, 2, “Array”]; You may also use new keyword to create array objects: var JSArr = new array (1,2,3,”String”);

Can you have a mixed data type array in Java?

Yes, We can use mixed datatypes in a single array.

How do you create an array with multiple data types in TypeScript?

Use a union type to define an array with multiple types in TypeScript, e.g. const arr: (string | number)[] = ['a', 1] . A union type is formed from two or more other types. The array in the example can only contain values of type string and number .

Can array have different data types JavaScript?

JavaScript arrays can indeed contain any and all types of data. An array may contain other objects (including other arrays) as well as any number of primitive values like strings, null , and undefined .


1 Answers

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}
like image 153
Gustavo Niemeyer Avatar answered Sep 28 '22 13:09

Gustavo Niemeyer