6

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?

nemo
  • 55,207
  • 13
  • 135
  • 135
Mark Hayden
  • 515
  • 4
  • 13

3 Answers3

9

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"})
Mark Hayden
  • 515
  • 4
  • 13
7

In your case, it would be:

bson.M{"$or": []bson.M{
    {"dependencies.provider_id": "abc"},
    {"actions.provider_id": "abc"},
}}
ANisus
  • 74,460
  • 29
  • 162
  • 158
  • GAH, I knew it was something simple, was missing the bson.M on each of the key/values. You are awesome, thanks so much. – Mark Hayden Aug 27 '14 at 03:11
  • got another quick question while I wait 7 minutes to accept your answer. Is there a simple way to "push" into an existing bson varaible? so say the above is query := .... then i wanted to run an if and add more to it potentially. – Mark Hayden Aug 27 '14 at 03:13
  • @MarkHayden Feel free to open a new question. – nemo Aug 27 '14 at 03:15
  • 1
    @MarkHayden Welcome! Yes, that is quite simple. `bson.M` has the underlying type of `map[string]interface{}`, so you can just treat it as a normal map: `query["$or"] = append(query["$or"].([]bson.M), bson.M{"another_or": "abc"})` – ANisus Aug 27 '14 at 03:18
  • @MarkHayden I removed the unnecessary `bson.M` as they are implicit set by `[]bson.M`. – ANisus Aug 27 '14 at 03:26
1

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"})
gold three
  • 661
  • 1
  • 8
  • 10