V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
amyangfei
V2EX  ›  MongoDB

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

  •  
  •   amyangfei · Aug 28, 2013 · 5333 views
    This topic created in 4637 days ago, the information mentioned may be changed or developed.
    来自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 replies    1970-01-01 08:00:00 +08:00
    hepochen
        1
    hepochen  
       Oct 18, 2013   ❤️ 1
    一般情况下,性能差距不大。直接遍历find获得cursor,实际上(pymongo)会获取一些数据,等这些数据不够用了,然后再去获取。跟limit产生的信息流实际上是一样的。

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

    但不管怎么样,这种场景下,不建议直接用find这个cursor,设一个最大的limit值也好(一般情况下)。如果你自己不小心手滑,没有终止迭代,并且collection的数据量很大……
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2883 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 02:31 · PVG 10:31 · LAX 19:31 · JFK 22:31
    ♥ Do have faith in what you're doing.