duangou1551
2018-04-05 10:46
浏览 371

使用gopkg.in/mgo.v2作为字符串的golang中的自定义mongodb命令

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

图片转代码服务由CSDN问答提供 功能建议

我想知道,是否有运行我自己构造为字符串变量的命令(或查询)的条件 使用“ mgo”。

类似这样的东西:

  c:= session.DB(DBNAME).C(COLLECTION)
c.RUN_COMMAND_AS_STRING(“ find  ({username:'vahid'})“)
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doxqszx09742 2018-04-13 03:37
    已采纳

    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)
    
    已采纳该答案
    打赏 评论
  • doubei2231 2018-04-07 02:25

    Here's what I like to use:

    func dbInsert(collection string, insert bson.M, session *mgo.Session) error {
        c := session.DB(your_DB).C(collection)
        err := c.Insert(insert)
        return err
    }
    
    func dbUpsert(collection string, selector bson.M, update bson.M, session *mgo.Session) (*mgo.ChangeInfo, error) {
        c := session.DB(your_DB).C(collection)
        info, err := c.Upsert(selector, update)
        return info, err
    }
    
    func dbFindOne(collection string, findBson bson.M, selectBson bson.M, session *mgo.Session) (map[string]interface{}, error) {
        c := session.DB(your_DB).C(collection)
        getMap := make(map[string]interface{})
        err := c.Find(findBson).Select(selectBson).One(&getMap)
        return getMap, err
    }
    
    func dbFindAll(collection string, findBson bson.M, selectBson bson.M, session *mgo.Session) (map[string]interface{}, error) {
        c := session.DB(your_DB).C(collection)
        getMap := make(map[string]interface{})
        err := c.Find(findBson).Select(selectBson).All(&getMap)
        return getMap, err
    }
    
    func dbUpdate(collection string, selector bson.M, update bson.M, session *mgo.Session) error {
        c := session.DB(your_DB).C(collection)
        setBson := bson.M{};
        setBson["$set"] = update;
        //
        updateError := c.Update(selector, setBson)
        //
        return updateError
    }
    
    func dbRemoveOne(collection string, selector bson.M, session *mgo.Session) error {
        c := session.DB(your_DB).C(collection)
        removeError := c.Remove(selector)
        return removeError
    }
    
    func dbRemoveAll(collection string, selector bson.M, session *mgo.Session) (*mgo.ChangeInfo, error) {
        c := session.DB(your_DB).C(collection)
        removeInfo, removeError := c.RemoveAll(selector)
        return removeInfo, removeError
    }
    

    Here's a sample query for find:

    //FIND ONE:
    employeeInfo, err := dbFindOne("employees", bson.M{"name": "john"}, bson.M{"salary": 1, "homeCity": 1}, mongo_session)
    
    if err != nil {
        fmt.Println("Error getting employee info: ", err)
    }else{
        //you can get the salary as an int:
        salary := employeeInfo["salary"].(int)
    
        //or get their homeCity as a string:
        homeCity := employeeInfo["homeCity"].(string)
    }
    

    This for instance finds the "salary" of employee named "john" in the collection "employees".

    All the methods in the snippet work in almost the same exact way as dbFindOne().

    Hope this helps!

    打赏 评论

相关推荐 更多相似问题