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

2

21

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

When working in GoLang using the package labix.org/v2/mgo and I do for example:

query := db.C("client").Find();

It complains that it requires input in the form of an interface. All I need to do is retrieve all documents and iterate through them and display each one for now. How do I achieve this effect? All examples I have seen seem to have filters in place.

Subtreasury answered 10/7, 2014 at 15:53 Comment(0)
S
47

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) 
    }
Subtreasury answered 10/7, 2014 at 16:2 Comment(3)
getting nil from a database is a weak reason to panicJolt
however will get the user of the above code to actually read it and decide how to deal with the nil. From the perspective of someone coming here and copy/pasting that code being highly likely, this is a good way to get them to at least think about it....Quadriplegia
you can use db.c("client").Find(bson.M{}).All(&result)Skite
I
0
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)

}
Idolater answered 17/10, 2018 at 5:58 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.