当 primitive.A 是 bson []interface 时,如何将 mongo-go-driver 作为 bson 数组的输出反序列化为 []interface{}

How do I deserialize output from mongo-go-driver as bson array into a []interface{} when primitive.A is bson []interface

我有一个映射[string]接口{},它是从使用新 mongo-go-driver

的 mongo 查询生成的

我想处理映射中的某些值并替换属于聚合键的值中的 £ 字符

这是地图:

result2 = map[aggregate:[map[£match:map[Source:Cities]] map[£sort:map[Order:1]]] collection:aggregate_stats db:stats]

遍历地图:

    for key, value := range result2 {
        fmt.Println("key from result2:", key, " || ", "value from result 2:", value)
        if key == "aggregate" {
            fmt.Println("FOUND AGGREGATE || ", "value:", value, " || type: ", reflect.TypeOf(value))
        }
        if valueMSI, ok := value.([]interface{}); ok {
            fmt.Println("Working", valueMSI)
            fmt.Println(reflect.TypeOf(valueMSI))
        }
    }

现在,在检查聚合键的 if 语句中,第一个 print 语句的输出给出的类型为:

primitive.A

但是打印出来的时候好像是地图的[]界面{}? [查看结果2]

考虑到这一点,为什么不计算第二个 if 语句?

这是否意味着 primitive.A != 接口数组?

在文档 https://godoc.org/go.mongodb.org/mongo-driver/bson/primitive 中,类型 A 定义为 "An A represents a BSON array. This type can be used to represent a BSON array in a concise and readable manner. It should generally be used when serializing to BSON. For deserializing, the RawArray or Array types should be used."

我该怎么做?我想访问聚合键的值?

您可以使用 conversion expression 将类型 primitive.A 的值转换为 []interface{},其形式为 T(x).

所以在你的情况下你可以这样做:

for key, value := range result2 {
    fmt.Println("key from result2:", key, " || ", "value from result 2:", value)
    if key == "aggregate" {
        fmt.Println("FOUND AGGREGATE || ", "value:", value, " || type: ", reflect.TypeOf(value))
    }
    if pa, ok := value.(primitive.A); ok {
        valueMSI := []interface{}(pa)
        fmt.Println("Working", valueMSI)
        fmt.Println(reflect.TypeOf(valueMSI))
    }
}

如文档中所述,在任何这些情况下,您都可以将非常量值 x 转换为类型 T(我已经强调了与您的问题相关的情况):

  • x is assignable to T.
  • ignoring struct tags (see below), x's type and T have identical underlying types.
  • ignoring struct tags (see below), x's type and T are pointer types that are not defined types, and their pointer base types have identical underlying types.
  • x's type and T are both integer or floating point types.
  • x's type and T are both complex types.
  • x is an integer or a slice of bytes or runes and T is a string type.
  • x is a string and T is a slice of bytes or runes.

关于 underlying types 的一点(强调已添加):

Each type T has an underlying type: If T is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T itself. Otherwise, T's underlying type is the underlying type of the type to which T refers in its type declaration.

由于 primitive.A 是使用 类型文字 []interface{} 定义的,因此它具有与 相同的基础类型 []interface{}.

  • []interface{} 的基础类型是 []interface{}
  • primitive.A 的基础类型是 []interface{}