如何在Go的mongo-driver中为options.FindOne()设置限制?

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

How to Set Limit for options.FindOne() in go mongo-driver

问题

我看到Find()函数有一个SetLimit()方法,但是我没有看到为FindOne()设置限制的选项。由于我们在FindOne()中只搜索单个结果,所以我们甚至不需要限制它吗?它会自动处理限制吗?

我尝试使用options.FindOne()来设置限制,但是我没有找到方法来实现。

英文:

I see there is a way to SetLimit() for Find() func, But I don't see any options to set limit for FindOne() , Since we are searching single result out of FindOne() we don't even have to limit it ? Automatically it handles limit ?

Tried setting limit using 1options.FindOne()` , But I do not see a way to do that .

答案1

得分: 1

这是要翻译的内容:

这个行为没有在文档中记录,但是根据常识,Collection.FindOne() 的行为类似于 Limit=1Collection.FindOne() 的返回值不能访问多个结果文档,这就是为什么 options.FindOne 甚至没有 SetLimit() 方法。

如果你查看源代码,可以看到:

// 为了确保只返回一个文档并且不保持游标打开,无条件地发送一个限制。
findOpts = append(findOpts, options.Find().SetLimit(-1))

注意到 FindOptions.Limit 的文档中写道:

// Limit 是返回的最大文档数。默认值为 0,表示返回匹配筛选条件的所有文档。负数的 Limit 指定结果文档应在一个批次中返回。默认值为 0。
Limit *int64
英文:

It's not documented, but it's common sense that Collection.FindOne() implies a behavior of that of Limit=1. The return value of Collection.FindOne() doesn't give access to multiple result documents, that's why options.FindOne doesn't even have a SetLimit() method.

If you check the source code, it's in there:

// Unconditionally send a limit to make sure only one document is returned and the cursor is not kept open
// by the server.
findOpts = append(findOpts, options.Find().SetLimit(-1))

Note that FindOptions.Limit documents that:

// Limit is the maximum number of documents to return. The default value is 0, which means that all documents matching the
// filter will be returned. A negative limit specifies that the resulting documents should be returned in a single
// batch. The default value is 0.
Limit *int64

huangapple
  • 本文由 发表于 2022年10月31日 14:42:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/74259580.html
匿名

发表评论

匿名网友

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

确定