Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all documents in a collection with mongo go driver

I checked out the answer here but this uses the old and unmaintained mgo. How can I find all documents in a collection using the mongo-go-driver?

I tried passing a nil filter, but this does not return any documents and instead returns nil. I also checked the documentation but did not see any mention of returning all documents. Here is what I've tried with aforementioned result.

client, err := mongo.Connect(context.TODO(), "mongodb://localhost:27017")
coll := client.Database("test").Collection("albums")
if err != nil { fmt.Println(err) }
// we can assume we're connected...right?
fmt.Println("connected to mongodb")

var results []*Album
findOptions := options.Find()
cursor, err := coll.Find(context.TODO(), nil, findOptions)
if err != nil {
   fmt.Println(err) // prints 'document is nil'
}

Also, I'm about confused about why I need to specify findOptions when I've called the Find() function on the collection (or do I not need to specify?).

like image 289
Kelly Flet Avatar asked Feb 25 '19 23:02

Kelly Flet


1 Answers

Here is what I came up with using the official MongoDB driver for golang. I am using godotenv (https://github.com/joho/godotenv) to pass the database parameters.

//Find multiple documents
func FindRecords() {
    err := godotenv.Load()

    if err != nil {
        fmt.Println(err)
    }

    //Get database settings from env file
    //dbUser := os.Getenv("db_username")
    //dbPass := os.Getenv("db_pass")
    dbName := os.Getenv("db_name")
    docCollection := "retailMembers"

    dbHost := os.Getenv("db_host")
    dbPort := os.Getenv("db_port")
    dbEngine := os.Getenv("db_type")

    //set client options
    clientOptions := options.Client().ApplyURI("mongodb://" + dbHost + ":" + dbPort)
    //connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)
    if err != nil {
        log.Fatal(err)
    }

    //check the connection
    err = client.Ping(context.TODO(), nil)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Connected to " + dbEngine)
    db := client.Database(dbName).Collection(docCollection)

    //find records
    //pass these options to the Find method
    findOptions := options.Find()
    //Set the limit of the number of record to find
    findOptions.SetLimit(5)
    //Define an array in which you can store the decoded documents
    var results []Member

    //Passing the bson.D{{}} as the filter matches  documents in the collection
    cur, err := db.Find(context.TODO(), bson.D{{}}, findOptions)
    if err !=nil {
        log.Fatal(err)
    }
    //Finding multiple documents returns a cursor
    //Iterate through the cursor allows us to decode documents one at a time

    for cur.Next(context.TODO()) {
        //Create a value into which the single document can be decoded
        var elem Member
        err := cur.Decode(&elem)
        if err != nil {
            log.Fatal(err)
        }

        results =append(results, elem)

    }

    if err := cur.Err(); err != nil {
        log.Fatal(err)
    }

    //Close the cursor once finished
    cur.Close(context.TODO())

    fmt.Printf("Found multiple documents: %+v\n", results)


}
like image 178
Isaac Muthui Avatar answered Oct 12 '22 16:10

Isaac Muthui