【问题标题】:Difference between cursor.count() and cursor.size() in MongoDBMongoDB 中 cursor.count() 和 cursor.size() 之间的区别
【发布时间】:2012-08-09 10:25:33
【问题描述】:

MongoDB的DBCursorcursor.count()cursor.size()方法有什么区别?

【问题讨论】:

    标签: java mongodb mongodb-java mongo-java


    【解决方案1】:

    来自Javadoc of the MongoDB Java Driver,它说:

    DBCursor.count():统计与查询匹配的对象数。这 考虑限制/跳过。

    DBCursor.size():统计与查询匹配的对象数。这 确实考虑了限制/跳过。

    【讨论】:

    • 两者似乎是相同的......为什么他们仍然引入了 2 种这样的方法?两者之间有什么性能差异吗?
    • 我怀疑区别在于 does not takedoes take 限制/跳过考虑。
    • 他们不一样。一个考虑限制/跳过,但其他不考虑。
    • @RemonvanVliet 有时,当您感到信息量过大时,您会感到不知所措。 ;)
    【解决方案2】:

    我想指出的不仅仅是一个答案,我们的团队面临“混合”这两个问题。

    我们有这样的事情:

    DBCursor cursor = collection.find(query).limit(batchSize);
    
    logger.info("{} items found.", cursor.count());
    
    while (cursor.hasNext()) {
    ...
    }
    

    原来调用cursor.count()方法后,限制被忽略(请看this其他问题),我们打算知道返回了多少项查询,所以我们应该调用 cursor.size() 方法,因为调用 count 确实会产生不良的附带影响。

    我希望这对其他人有所帮助,因为找到我们所面临问题的根源并不容易。

    【讨论】:

    • 你是说cursor.count()不仅忽略了记录的限制,而且实际上从游标中删除了限制,因此诸如迭代游标等后续操作的行为就像没有设置限制一样?
    【解决方案3】:

    当我第一次阅读有关cursor.countcursor.size 之间区别的文档时,我同样感到困惑,因为我不明白不考虑skiplimit 意味着什么。我发现这篇文章很有帮助read more here。我认为以下示例说明了差异

    // by default cursor.count ignores limit or skip. note that 100 records were returned despite the limit being 5
    > db.restaurants.find( { "cuisine": "Bakery", "address.zipcode": "10462" } ).limit(5).count();
    100
    // if you want to consider limits and skips, then add an optional parameter specifying so
    > db.restaurants.find( { "cuisine": "Bakery", "address.zipcode": "10462" } ).limit(5).count(true);
    5
    // cursor.size on the other hand abides by limits and skips
    > db.restaurants.find( { "cuisine": "Bakery", "address.zipcode": "10462" } ).limit(5).size();
    5
    

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 2019-01-30
      • 2019-08-06
      • 1970-01-01
      • 2017-01-31
      • 1970-01-01
      相关资源
      最近更新 更多