本文介绍了使用 mgo 的非结构化 MongoDB 集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Go 非常陌生.从我在 mGo 的例子中看到的,为了查询一个集合然后从中读取,你必须预先定义将在结构中返回的数据.

I'm VERY new to Go. From what I've seen in the examples of mGo, in order to query a collection and then read from it, you have to predefine the data that will be coming back in a struct.

type Person struct {
    ID        bson.ObjectId `bson:"_id,omitempty"`
    Name      string
    Phone     string
    Timestamp time.Time
}

在 PHP 中,文档被分配给一个数组.这是完美的,因为一个记录可能有一组完全不同的键(可能不包含姓名或电话,但包含电子邮件),我可以直接访问它而无需设置预定义的类/结构/变量.

In PHP, the document was assigned to an array. This was perfect as one record may have completely different set of keys (may not contain Name or Phone but contain Email) and I could access it directly without setting up a predefined class / struct / variable.

有没有办法在 Go/mGo 中做同样的事情?

Is there a way to do the same in Go / mGo?

推荐答案

有多种方法可以解决这个问题.

There are multiple ways you can handle this.

使用地图:

var m bson.M
err := collection.Find(nil).One(&m)
check(err)
for key, value := range m {
    fmt.Println(key, value)
}

请注意,就 mgo 而言,bson.M 没有什么特别之处.它只是一个 map[string]interface{} 类型,您可以定义自己的地图类型并将它们与 mgo 一起使用,即使它们具有不同的值类型.

Note that there's nothing special about bson.M as far as mgo is concerned. It's just a map[string]interface{} type, and you can define your own map types and use them with mgo, even if they have a different value type.

使用文档切片:

bson.D 是 mgo 内部已知的切片,它存在既是为了提供更有效的机制,也是为了提供一种保留键顺序的方法,MongoDB 在某些情况下(例如,在定义索引时)会使用这种方法.

The bson.D is a slice that is internally known to mgo, and it exists both to offer a more efficient mechanism and to offer a way to preserve the ordering of keys, which is used by MongoDB in some circumstances (for example, when defining indexes).

例如:

var d bson.D
err := collection.Find(nil).One(&d)
check(err)
for i, elem := range d {
    fmt.Println(elem.Name, elem.Value)
}

使用内联地图字段

,inline bson flag 也可以使用在地图字段中,这样您就可以拥有蛋糕并吃掉它.换句话说,它允许使用结构体,以便于操作已知字段,同时允许通过内联映射处理未知字段.

The ,inline bson flag can also be used in a map field, so that you can have your cake and eat it too. In other words, it enables using a struct so that manipulating known fields is convenient, and at the same time allows dealing with unknown fields via the inline map.

例如:

type Person struct {
    ID        bson.ObjectId `bson:"_id,omitempty"`
    Name      string
    Phone     string
    Extra     bson.M `bson:",inline"`
}

这篇关于使用 mgo 的非结构化 MongoDB 集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:18