如何处理从mongo返回的任意散列(使用mgo)? [英] How do I deal with an arbitrary hash returned from mongo in go (using mgo)?
问题描述
在ruby中,我只是将整个返回的记录视为任意散列和交易与它按键。
您可以使用通用映射,例如:
var result map [string] interface {}
err:= collection.Find(query).One(& result)
您会发现使用 bson.M
的人,其中也是具有相同基础类型的地图。不过,没有什么特别的 bson.M
。这只是地图的一个简短而方便的名字。您可以创建自己的便捷名称,或使用上面示例中的普通映射。
另一种访问不带定义模式的文档的方法是使用 bson.D
来代替上面的地图类型。 bson.D
在文档中元素的顺序是相关的时候最为有用,或者如果您想稍微减少操作开销(地图的处理效果会更加昂贵对其性质)。 bson.D
类型是带有键/值对的一段结构值。不同于 bson.M
, bson.D
是特殊的,并且由mgo / bson包内部处理。
All of the references I can find construct a struct to hold the return values, assuming that each returned record has the same schema. If they're really documents and don't have a consistent schema other than maybe a few queryable consistent metadata attributes, how can I handle that return value?
e.g.: this https://groups.google.com/forum/#!msg/mgo-users/KirqfCSlKFc/t2l3l4yxFRwJ assumes that you have an array of timestamps. What if it's an array where some of the values are timestamps and some are strings?
In ruby, I'd just treat the whole returned record as an arbitrary hash and deal with it key by key. What can I do with it in go?
You can use a generic map, for example:
var result map[string]interface{}
err := collection.Find(query).One(&result)
You'll find people using bson.M
, which is also a map with that same underlying type. There's nothing special about bson.M
, though. It's just a short and convenient name for a map. You can create your own convenient name, or use a plain map as in the example above.
Another way to have access to documents without a defined schema is using bson.D
in place of the map type above. bson.D
is most useful when the order of elements in the document is relevant, or if you want to reduce the operation overhead slightly (maps are a bit more expensive to handle due to their nature). The bson.D
type is a slice of struct values with Key/Value pairs. Unlike bson.M
, bson.D
is special and is handled internally by the mgo/bson package.
这篇关于如何处理从mongo返回的任意散列(使用mgo)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!