简体   繁体   English

我可以只获取 Cursor 对象(pymongo)中的第一项吗?

[英]Can I just get the first item in a Cursor object (pymongo)?

so I created a Cursor object by having所以我创建了一个 Cursor 对象

cdb=self.mongo['bleh_bleh_bleh_setup_here']
data=cdb[collection].find(query_commands_here)

Don't worry about the syntax above.不要担心上面的语法。 Just assume that I can successfully create such cursor object假设我可以成功创建这样的游标对象

I know I can do a for loop to iterate through the object, but all I want is the very first item of this object.我知道我可以做一个for循环来遍历对象,但我想要的只是这个对象的第一个项目。 Is there a more efficient way than looping through?有没有比循环更有效的方法?

EDIT:编辑:

to make things more clear, the 'bleh_bleh_bleh_setup_here' is simply path to connect to the desired mongoDB, and 'query_commands_here' are queries like {field1:{'$gt':num1}, field2:{'$ne':num2}} that sort of things.为了让事情更清楚,'bleh_bleh_bleh_setup_here' 只是连接到所需 mongoDB 的路径,'query_commands_here' 是像{field1:{'$gt':num1}, field2:{'$ne':num2}}那种东西。 The line线

data=cdb[collection].find(query_commands_here)

will give me a Cursor object that I can iterate with a for loop.会给我一个 Cursor 对象,我可以用for循环进行迭代。 So things like所以像

for item in data:
    print item

will print out each of the entry in the object.将打印出对象中的每个条目。 It works nicely.它工作得很好。 However, according to the documentation, this cursor object should have method called .hasNext() , which should return True if there's a next entry.但是,根据文档,这个游标对象应该有一个名为.hasNext()方法,如果有下一个条目,它应该返回 True 。 So far, I haven't found a way to get it to work for some odd reason.到目前为止,由于某些奇怪的原因,我还没有找到让它工作的方法。 data.next() does give me an entry though. data.next()确实给了我一个条目。 I want to make sure I can have that condition to make sure I don't call .next() for a cursor object that contains nothing, though I don't foresee this kind of situation happening, but I would assume it'd occur at some point.我想确保我可以有这样的条件,以确保我不会为一个不包含任何内容的游标对象调用.next() ,尽管我没有预见到这种情况会发生,但我认为它会发生在某一点。

.find_one() would return you a single document matching the criteria: .find_one()会返回一个符合条件的文档:

cdb[collection].find_one(query_commands_here)

Note that the PyMongo Cursor does not have a hasNext() method.请注意, PyMongo Cursor没有hasNext()方法。 What I would do is to call cursor.next() and handle the StopIteration exception:我要做的是调用cursor.next()并处理StopIteration异常:

try:
    record = cursor.next()
except StopIteration:
    print("Empty cursor!")

You can also do the following (without having to handle the StopIteration exception) :您还可以执行以下操作(无需处理StopIteration异常)

cur = cdb[collection].find(query_commands_here)
record = next(cur, None)
if record:
    # Do your thing

This works because python's built in next() will return the default value when it hits the end of the iterator.这是有效的,因为 python 内置的 next() 将在到达迭代器末尾时返回默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM