Search code examples
mongodbgomgo

Custom mongodb command in golang using gopkg.in/mgo.v2 as string


I was wondering, is there anyway to run my own command (or query) which I have constructed as a string variable using "mgo" in go.

Something like this:

c := session.DB(DBNAME).C(COLLECTION)
c.RUN_COMMAND_AS_STRING("find({username:'vahid'})")

Solution

  • is there anyway to run my own command (or query) which I have constructed as a string variable using "mgo" in go.

    You can invoke MongoDB find command, and parsing string of query filter to map[string]interface{}.

    For example:

    db := session.DB("databaseName")
    
    queryString := `{"username":"sergio"}`
    var filter map[string]interface{} 
    err = json.Unmarshal([]byte(queryString), &filter)
    
    result := bson.M{}
    err = db.Run(bson.D{{"find", "collectionName"}, {"filter", filter}}, &result)
    fmt.Println(result)
    

    Alternatively, instead of using find(), depending on your use case, you can also use MongoDB Aggregation Pipeline.

    For example:

    pipeString := `[{"$match":{"username":"sergio"}}, {"$project":{"newfield":"$username"}}]`
    
    pipe := []bson.M{}
    err = json.Unmarshal([]byte(pipeString), &pipe)
    
    coll := session.DB("databaseName").C("collectionName")
    response := []bson.M{}
    err = coll.Pipe(pipe).All(&response)  
    fmt.Println(response)