2

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?

Mari
  • 155
  • 1
  • 9

1 Answers1

1

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
}

// Note: Cursor.All() closes the cursor
icza
  • 389,944
  • 63
  • 907
  • 827
  • Hi, thank you for replying to my question. Will Cursor.Next() return an error if there are no documents to iterate over then? I'm very new to Go, sorry if my questions are silly. – Mari Nov 03 '22 at 21:56
  • `Cursor.Next()` returns a single `bool` value, it doesn't return any errors. If there are no results, it returns `false`. – icza Nov 03 '22 at 21:58