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

JCh*_*hao 15 python mongodb pymongo

所以我创建了一个Cursor对象

cdb=self.mongo['bleh_bleh_bleh_setup_here']
data=cdb[collection].find(query_commands_here)
Run Code Online (Sandbox Code Playgroud)

不要担心上面的语法.假设我可以成功创建这样的游标对象

我知道我可以for循环遍历对象,但我想要的只是这个对象的第一项.有没有比循环更有效的方法?

编辑:

为了使事情更清楚,'bleh_bleh_bleh_setup_here'只是连接到所需mongoDB的路径,'query_commands_here'就是这样的查询{field1:{'$gt':num1}, field2:{'$ne':num2}}.这条线

data=cdb[collection].find(query_commands_here)
Run Code Online (Sandbox Code Playgroud)

将给我一个Cursor对象,我可以循环迭代for.所以像

for item in data:
    print item
Run Code Online (Sandbox Code Playgroud)

将打印出对象中的每个条目.它工作得很好.但是,根据文档,此游标对象应该有调用的方法.hasNext(),如果有下一个条目,则应该返回True.到目前为止,我还没有找到一种方法让它因某些奇怪的原因而起作用.data.next()确实给了我一个入口.我想确保我可以有这个条件,以确保我不要求.next()一个不包含任何内容的游标对象,虽然我不预见会发生这种情况,但我会认为它会在某个时刻发生.

ale*_*cxe 16

.find_one() 会返回符合条件的单个文档:

cdb[collection].find_one(query_commands_here)
Run Code Online (Sandbox Code Playgroud)

请注意,PyMongo Cursor没有hasNext()方法.我要做的是调用cursor.next()和处理StopIteration异常:

try:
    record = cursor.next()
except StopIteration:
    print("Empty cursor!")
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。我通过使用 c[i] 找到了一种解决方法,其中 i 是索引 #。这调用了 __getitem__ 函数,它非常适合我的情况。 (2认同)