How do you select all records from a mongodb collection in golang using mgo

后端 未结 2 1471
轻奢々
轻奢々 2021-02-18 19:49

In MongoDB doing something like db.mycollection.find() returns all documents in a collection.

When working in GoLang using the package labix.org/v2/

相关标签:
2条回答
  • 2021-02-18 19:56
    func (uc UserController) GetUsersList(w http.ResponseWriter,r *http.Request,p httprouter.Params){
    
    var u []models.User
    // Fetch user
    if err := uc.session.DB("mydb").C("users").Find(nil).All(&u); err != nil {
    
        w.WriteHeader(404)
        fmt.Println("Results All: ", u) 
        return
    }
    uj, _ := json.Marshal(u)
    
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(200)
    fmt.Fprintf(w, "%s", uj)
    
    }
    
    0 讨论(0)
  • 2021-02-18 20:02

    Found a solution:

        var results []client
    
        err := db.C("client").Find(nil).All(&results)
        if err != nil {
            // TODO: Do something about the error
        } else {
            fmt.Println("Results All: ", results) 
        }
    
    0 讨论(0)
提交回复
热议问题