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

后端 未结 2 1459
轻奢々
轻奢々 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)
    
    }
    

提交回复
热议问题