mongodb 如何在go mongo-driver中为options.FindOne()设置限制

toiithl6  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(108)

我看到有一种方法SetLimit()Find()函数,但我没有看到任何选项来设置FindOne()的限制,因为我们正在搜索FindOne()的单一结果,我们甚至没有限制它?自动处理限制?
尝试使用1options.FindOne()'设置限制,但我找不到这样做的方法。

nuypyhwy

nuypyhwy1#

虽然没有文档说明,但Collection.FindOne()暗示了Limit=1的行为,这是常识。Collection.FindOne()的返回值不给予访问多个结果文档,这就是为什么options.FindOne甚至没有SetLimit()方法。
如果你检查源代码,它在那里:

// 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))

请注意,FindOptions.Limit记录了以下内容:

// 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

相关问题