Search code examples
gomgo

Parse a string without fixed set of keys for MongoDB find query


I have an API where the user will pass the query parameters they want to pass it to MongoDB. The API will take the string from the request parameter and pass it directly to Mongo find query. The query string won't have any fixed set of keys. It can have the one of the following structures -

{"name": "foo"}
{"name": "foo", "source": "bar"}
{"source": "oof", "place": "rab"}
...

How do I parse this string, so that I can directly use like this -

collection.Find(MyQuery).All(&m)

Solution

  • You simply use json.Unmarshal on the json and convert it to bson.M then call Find like usual, example:

    q := bson.M{}
    if err := json.Unmarshal([]byte(json_str), &q); err != nil {
        panic(err)
    }
    collection.Find(q).All(&m)
    

    But since this is coming from an API, you should do some clean up before you pass q to Find.