V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
amyangfei
V2EX  ›  MongoDB

关于 db.collection.find() 查询返回 cursor 的一个疑问

  •  
  •   amyangfei · 2013-08-28 18:37:11 +08:00 · 4792 次点击
    这是一个创建于 3895 天前的主题,其中的信息可能已经有所发展或是发生改变。
    来自MongoDB文档的一句话:db.collection.find() RETURNS A cursor to the documents that match the query criteria. When the find() method “returns documents,” the method is actually returning a cursor to the documents.

    举一个例子,假设collection中的数据量很大很大,那么db.collection.find(<criteria>, limit=40)的效率和cursor = db.collection.find(<criteria>),然后for x in cursor 这种方法的效率比起来,后一种方法的效率会低么,具体的差别有多大?

    实际的应用场景是通过 db.collection.find(<criteria>) 返回一个cursor,由于业务的需要,从结果集中取出的结果数量是不定的,通过迭代器选取一些结果满足需求之后就会终止迭代。
    1 条回复    1970-01-01 08:00:00 +08:00
    hepochen
        1
    hepochen  
       2013-10-18 11:31:28 +08:00   ❤️ 1
    一般情况下,性能差距不大。直接遍历find获得cursor,实际上(pymongo)会获取一些数据,等这些数据不够用了,然后再去获取。跟limit产生的信息流实际上是一样的。

    归根结底是在于应用场景的索引是如何建的?如果数据都属于热数据,find or limit,没有什么差别,基本上可以认为是从内存中取的。

    但不管怎么样,这种场景下,不建议直接用find这个cursor,设一个最大的limit值也好(一般情况下)。如果你自己不小心手滑,没有终止迭代,并且collection的数据量很大……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5573 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 06:48 · PVG 14:48 · LAX 23:48 · JFK 02:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.