使用mgo的非结构化MongoDB集合 [英] Unstructured MongoDB collections with mgo
问题描述
我非常喜欢Go。从我在mGo的例子中看到的,为了查询一个集合然后从它读取,你必须预先定义将要返回到结构中的数据。
类型Person结构{
ID bson.ObjectId`bson:_ id,omitempty`
名称字符串
电话字符串
时间戳time.Time
}
在PHP中,文档被分配给一个数组。这是完美的,因为一个记录可能有完全不同的一组键(可能不包含名称或电话,但包含电子邮件),我可以直接访问它,而无需设置预定义的类/结构/变量。
有没有办法在Go / mGo中执行相同的操作?
处理此事。
使用地图:
err:= collection.Find(nil).One(& m)
check(err)
for key,value:= range m {
fmt.Println(key,value)
}
请注意,没有什么特别的关于 bson.M 至于mgo而言。它只是一个 map [string]接口{}
类型,您可以定义自己的地图类型并将它们用于mgo,即使它们具有不同的值类型。 p>
使用文档片段: bson.D 是mgo内部已知的一个片段,它存在于提供更有效的机制并提供一种方式来保留键的顺序,在某些情况下(例如,在定义索引时),MongoDB使用这些键。
例如:
var d bson.D
err:= collection.Find(nil).One(&d)
check(err)
for i,elem:=范围d {
fmt.Println(elem.Name,elem.Value)
}
使用内联地图字段
$ b $ <<> c $ c> / code> bson 标志也可以在地图字段中使用,以便ÿ你可以吃你的蛋糕,也可以吃它。换句话说,它可以使用一个结构体,以便操纵已知字段很方便,同时允许通过内联映射处理未知字段。
例如:
类型Person结构{
ID bson.ObjectId`bson:_ id,omitempty`
Name字符串
电话字符串
额外的bson.M`bson:,inline`
}
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
}
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.
Is there a way to do the same in Go / mGo?
There are multiple ways you can handle this.
Using a map:
var m bson.M
err := collection.Find(nil).One(&m)
check(err)
for key, value := range m {
fmt.Println(key, value)
}
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.
Using a document slice:
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).
For example:
var d bson.D
err := collection.Find(nil).One(&d)
check(err)
for i, elem := range d {
fmt.Println(elem.Name, elem.Value)
}
Using an ,inline map field
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.
For example:
type Person struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Name string
Phone string
Extra bson.M `bson:",inline"`
}
这篇关于使用mgo的非结构化MongoDB集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!