Mark Hayden
Mark Hayden

Reputation: 515

Golang BSON conversion

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?

Upvotes: 6

Views: 9659

Answers (3)

gold three
gold three

Reputation: 701

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"})

Upvotes: 1

Mark Hayden
Mark Hayden

Reputation: 515

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"})

Upvotes: 9

ANisus
ANisus

Reputation: 77925

In your case, it would be:

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

Upvotes: 7

Related Questions