mongodb,pymongo,聚合给出奇怪的输出(关于游标的东西) [英] mongodb, pymongo, aggregate gives strange output (something about cursor)

查看:25
本文介绍了mongodb,pymongo,聚合给出奇怪的输出(关于游标的东西)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取数据库中条目最多的人员列表.

I am trying get a list of people with the most entries in my database.

print db.points.aggregate(
   [
      {
         "$group":
                    {
                       "_id": "$created.user", 
                       "count":{"$sum":1}
                    }
      },
      {
         "$sort":
                   {"count":-1}
      }
   ]
)

条目如下所示:

{
   u'id': u'342902', 
   u'_id': ObjectId('555af76a029d3b1b0ff9a4be'), 
   u'type': u'node', 
   u'pos': [48.9979746, 8.3719741], 
   u'created': {
                  u'changeset': u'7105928', 
                  u'version': u'4', 
                  u'uid': u'163673', 
                  u'timestamp': u'2011-01-27T18:05:54Z', 
                  u'user': u'Free_Jan'
               }
}

我知道 created.user 存在并且可以通过其他方式访问.

I know that created.user exists and is otherwise accessible.

我得到的输出仍然是:

<pymongo.command_cursor.CommandCursor 对象位于 0x02ADD6B0>

我不应该得到一个排序列表吗?

Shouldn't I get a sorted list ?

推荐答案

聚合查询的结果是一个游标,就像普通的 find 查询一样.在 pymongo 的情况下,CommandCursor 是可迭代的,因此您可以执行以下任何操作:

The result of an aggregation query is a cursor, as for a regular find query. In case of pymongo the CommandCursor is iterable, thus you are able to do any of the following:

cursor = db.points.aggregate(...)

# Option 1
print(list(cursor))

# Option 2
for document in cursor:
    print(document)

注意:arun 注意到,在这两种情况下,即在您使用光标创建列表或在 for 循环中迭代之后,您将无法重新迭代光标.在这种情况下,如果您想在将来使用它,第一个选项会变得更好,因为您可以尽可能多地使用获得的列表,因为它已经在内存中.
无法重申的原因是游标实际上是在服务器上,并且它逐块发送数据,并且在向您发送所有数据(或服务器终止)后,游标被销毁.

Note: as arun noticed, in both cases, i.e. after you create a list out of the cursor, or iterate in the for loop, you will not be able to re-iterate over the cursor. In that case the first option becomes better, if you want to use it in future, as you can use the obtained list as much as you want, because it is in the memory already.
The reason of not being able to reiterate is that the cursor is actually on the server, and it send the data chunk-by-chunk, and after it has sent you all the data (or the server terminates) the cursor gets destroyed.

这篇关于mongodb,pymongo,聚合给出奇怪的输出(关于游标的东西)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆