Home > Net >  Golang: how to check if collection.Find didn't find any documents?
Golang: how to check if collection.Find didn't find any documents?

Time:11-04

I'm using Go Mongo documentation where it is explicitly written that with FindOne function, if no documents are matching the filter, ErrNoDocuments will be returned, however, this error is not returned if I use Find function and no documents are found. Is there a way to check that the cursor is empty without getting a list of all returned documents and then checking if the list is empty?

CodePudding user response:

You may simply call Cursor.Next() to tell if there are more documents. If you haven't iterated over any yet, this will tell if there's at least one result document.

Note that this will cause the first batch of the results to fetch though (but will not decode any of the result documents into any Go values).

Also note that Cursor.Next() would return false if an error would occur or the passed context.Context would expire.

Example:

var c *mongo.Collection // Acquire collection

curs, err := c.Find(ctx, bson.M{"your-query": "here"})
// handle error

hasResults := curs.Next(ctx)
if hasResults {
    // There are result documents
}

// Don't forget to close the cursor!

Although if you intend to decode the results, you might as well just call Cursor.All() and check the length of the result slice:

curs, err := c.Find(ctx, bson.M{"your-query": "here"})
// handle error

var results []YourType
err := curs.All(ctx, &results)
// Handle error

if len(results) > 0 {
    // There are results
}
  • Related