Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang BSON conversion

Tags:

mongodb

go

bson

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?

like image 784
Mark Hayden Avatar asked Aug 27 '14 03:08

Mark Hayden


People also ask

What is type conversion in Golang?

Introduction to Golang Type Conversion. In Go language, the type conversion is a way to change the data type of variable. We generally change the data from initially we defined to another type of data type for example if we have defined a variable as integer and same variable we are going to use for some other purposes.

How does the go driver handle conversions between BSON and go values?

In this guide, you can learn about how the Go Driver handles conversions between BSON and Go values. The process of converting a Go value to BSON is called marshalling, while the reverse process is called unmarshalling.

What is go BSON license?

License A module to aid developers to generate Go BSON class maps. The auto-generated code output utilises go.mongodb.org/mongo-driver/bson, and is ideal to be used to read/write into MongoDB.

What is package BSON in MongoDB?

Package bson is a library for reading, writing, and manipulating BSON. BSON is a binary serialization format used to store documents and make remote procedure calls in MongoDB.


1 Answers

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"})
like image 124
Mark Hayden Avatar answered Sep 21 '22 06:09

Mark Hayden