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

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

问题描述

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

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存在并且可以通过其他方式访问.

我得到的输出仍然是:

<pymongo.command_cursor.CommandCursor object at 0x02ADD6B0>

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

解决方案

聚集查询的结果是游标,就像常规的find查询一样.如果是pymongo,则CommandCursor是可迭代的,因此您可以执行以下任一操作:

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

# Option 1
print(list(cursor))

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

注意:

An entry looks like this :

{
   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'
               }
}

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

Still the output i get is:

<pymongo.command_cursor.CommandCursor object at 0x02ADD6B0>

Shouldn't I get a sorted list ?

解决方案

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)

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天全站免登陆