Golang:如何检查 collection.Find 是否未找到任何文档?

huangapple go评论80阅读模式
英文:

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

问题

我正在使用Go Mongo文档,其中明确写道,使用FindOne函数时,如果没有与筛选条件匹配的文档,将返回ErrNoDocuments错误。然而,如果我使用Find函数并且没有找到文档,该错误不会被返回。有没有一种方法可以检查游标是否为空,而不必获取所有返回的文档列表,然后检查列表是否为空?

英文:

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?

答案1

得分: 1

你可以简单地调用Cursor.Next()来判断是否还有更多的文档。如果你还没有遍历过任何文档,这将告诉你是否至少有一个结果文档。

请注意,这将导致结果的第一批被获取(但不会将任何结果文档解码为Go值)。

还要注意,如果发生错误或传递的context.Context过期,Cursor.Next()将返回false

示例:

var c *mongo.Collection // 获取集合

curs, err := c.Find(ctx, bson.M{"your-query": "here"})
// 处理错误

hasResults := curs.Next(ctx)
if hasResults {
    // 存在结果文档
}

// 不要忘记关闭游标!

不过,如果你打算解码结果,你也可以直接调用Cursor.All()并检查结果切片的长度:

curs, err := c.Find(ctx, bson.M{"your-query": "here"})
// 处理错误

var results []YourType
err := curs.All(ctx, &results)
// 处理错误

if len(results) > 0 {
    // 存在结果
}

// 注意:Cursor.All()会关闭游标
英文:

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

huangapple
  • 本文由 发表于 2022年11月4日 05:44:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/74309872.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定