有办法知道 .limit() 是否真的移除了任何文档吗?

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

Is there a way to know whether .limit() actually removes any documents?

问题

使用mongocxx驱动程序(C++项目)。

正在处理一个从查询中分页获取一些结果的mongodb查询。我试图返回前10个结果,同时通知是否有更多结果可以使用另一个查询获取(使用偏移量),以便通知接收方是否有更多文档可获取。结果在数据库查找查询后存储在std::vector中。

是否有一种优雅的方法可以做到这一点,最好不返回所有结果文档然后将向量大小与指定的页面限制进行比较?

当前查询(没有具体细节):

db.collection.find({"<some_field>" : <some value>}).limit(10);

然而,这种方法无法通知是否删除了任何文档,如果确切地找到了10个结果的情况下。目前我只是简单地返回完整的结果向量并遍历它,如果循环超过10次(并设置“more_items”布尔值为true),则中断。

英文:

Using mongocxx driver (c++ project).

Working on a mongodb query to paginate some results from a query. I'm trying to return the first 10 results, while also informing whether or not there are more results to fetch with another query (using an offset) - so as to inform the recipient if there are more documents to fetch. The results are stored in a std::vector after the db find query.

Is there any elegant way to do this, preferably without returning all the result documents and then comparing the vector size to the specified page limit?

Current query (without specifics):

db.collection.find({&quot;&lt;some_field&gt;&quot; : &lt;some value&gt;}).limit(10);

This, however, will not inform whether or not any documents were removed, in the case that exactly 10 results were found.

Currently I'm simply returning the full vector of results and looping through it, breaking if the loop goes over 10 iterations (and setting a "more_items" bool to true).

答案1

得分: 0

你有两种方法可以做到这一点:

  1. 计算查询找到的所有文档数量
db.collection.count({"<some_field>" : <some value>});

然后,如果找到的文档多于你所需的数量(这里是10个),你可以将“more_items”布尔值设置为true。

<br>

  1. 查找并设置限制为+1(这里是11个)
db.collection.find({"<some_field>" : <some value>}).limit(11);

这样可以找到11个文档或更少。
如果你找到了11个文档,这表示你的文档数超过了10(实际限制)。如果找到少于11个文档,那么你没有达到实际的限制文档数。

英文:

You have 2 ways to do this:

  1. Count all documents found by query:
db.collection.count({&quot;&lt;some_field&gt;&quot; : &lt;some value&gt;});

And then if there is more documents than you need (10 in here) - you can set "more_items" bool to true

<br>

  1. Find and set limit to +1 (11 in here):
db.collection.find({&quot;&lt;some_field&gt;&quot; : &lt;some value&gt;}).limit(11);

That way you find 11 documents or less.
If you find 11 documents - this indicates that you have more documents than 10 (actual limit). If you find less than 11 - then you don't have documents to reach actual limit.

huangapple
  • 本文由 发表于 2023年2月10日 16:59:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408874.html
匿名

发表评论

匿名网友

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

确定