How do I deal with an arbitrary hash returned from mongo in go (using mgo)?

huangapple go评论88阅读模式
英文:

How do I deal with an arbitrary hash returned from mongo in go (using mgo)?

问题

我可以帮你翻译以下内容:

我能找到的所有参考资料都构建了一个结构体来保存返回值,假设每个返回的记录都有相同的模式。如果它们真的是文档,并且除了一些可查询的一致元数据属性之外没有一致的模式,那么我该如何处理返回值呢?

例如:这个链接https://groups.google.com/forum/#!msg/mgo-users/KirqfCSlKFc/t2l3l4yxFRwJ 假设你有一个时间戳数组。如果它是一个数组,其中一些值是时间戳,一些值是字符串,该怎么办?

在Ruby中,我只会将整个返回的记录视为任意的哈希表,并逐个处理键值对。在Go中我该怎么做呢?

英文:

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?

答案1

得分: 2

你可以使用一个通用的map,例如:

var result map[string]interface{}
err := collection.Find(query).One(&result)

你会发现人们使用bson.M,它也是一个具有相同底层类型的map。bson.M并没有什么特别之处,它只是一个简短方便的map名称。你可以创建自己方便的名称,或者像上面的示例一样使用普通的map。

另一种在没有定义模式的情况下访问文档的方法是使用bson.D替代上面的map类型。当文档中元素的顺序很重要时,或者如果你想稍微减少操作开销(由于其特性,map的处理成本稍高),bson.D是最有用的。bson.D类型是一个带有键/值对的结构值的切片。与bson.M不同,bson.D是特殊的,并且由mgo/bson包在内部处理。

英文:

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.

huangapple
  • 本文由 发表于 2014年1月17日 21:19:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/21187057.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定