Golang BSON 转换

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

Golang BSON conversion

问题

我正在尝试将一个在Mongo中工作的查询转换为Golang中的BSON。我已经掌握了基本的内容并且可以正常工作,但是我在如何将更高级的or查询集成到其中的问题上遇到了困难。

有人能帮我转换以下查询吗?这应该能给我一个方向...不幸的是,我还没有找到很多关于除了评估和查询之外的示例。

这是在Mongo中的查询:

db.my_collection.find({"$or": [
      {"dependencies.provider_id": "abc"}, 
      {"actions.provider_id": "abc"}]})

这是在Golang/BSON中的查询:

bson.M{"dependencies.provider_id": "abc"}

我该如何正确引入or语句?

英文:

I am trying to convert a working mongo query to bson in golang. I have the basic stuff down and working but am struggling to figure out how to integrate more advanced or queries into the mix.

Anyone have a minute to help me convert the following query? It should hopefully give me the direction I need... Unfortunately I have not been able to find many examples outside of just evaluating and queries.

This works in mongo:

db.my_collection.find({"$or": [
      {"dependencies.provider_id": "abc"}, 
      {"actions.provider_id": "abc"}]})

This works in golang/bson:

bson.M{"dependencies.provider_id": "abc"}

How do I go about properly introducing the or statement?

答案1

得分: 9

以下是你要翻译的内容:

为了完整起见,这是我在上面的评论中提出的问题的完整示例。更大的目标是在Go语言中动态构建一个bson查询。非常感谢ANisus:

query := bson.M{}
query["origin"] = "test"
query["$or"] = []bson.M{}
query["$or"] = append(query["$or"].([]bson.M), bson.M{"abc": "1"})
query["$or"] = append(query["$or"].([]bson.M), bson.M{"def": "2"})
英文:

For completeness here is a full example of my last question in the comments above. The larger goal was dynamically building a bson query in go. Huge thanks to ANisus:

query := bson.M{}
query["origin"] = "test"
query["$or"] = []bson.M{}
query["$or"] = append(query["$or"].([]bson.M), bson.M{"abc": "1"})
query["$or"] = append(query["$or"].([]bson.M), bson.M{"def": "2"})

答案2

得分: 7

在你的情况下,它应该是:

bson.M{"$or": []bson.M{
    {"dependencies.provider_id": "abc"},
    {"actions.provider_id": "abc"},
}}
英文:

In your case, it would be:

bson.M{"$or": []bson.M{
	{"dependencies.provider_id": "abc"},
	{"actions.provider_id": "abc"},
}}

答案3

得分: 1

像这样

package main
import "github.com/globalsign/mgo/bson"

query := make([]map[string]interface{}, 0)
query = append(query, map[string]interface{}{"dependencies.provider_id": "abc"})
query = append(query, map[string]interface{}{"actions.provider_id": "abc"})
英文:

like this

package main
import "github.com/globalsign/mgo/bson"

query := make([]map[string]interface{}, 0)
query = append(query, map[string]interface{}{"dependencies.provider_id": "abc"})
query = append(query, map[string]interface{}{"actions.provider_id": "abc"})

huangapple
  • 本文由 发表于 2014年8月27日 11:03:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/25518297.html
匿名

发表评论

匿名网友

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

确定