Pymongo聚合不返回游标而是返回对象

时间:2015-10-02 15:14:31

标签: python mongodb pymongo

我正在使用pymongo编写代码,该代码使用聚合框架将一些数据保存在其他集合中。 代码是这样的:

from pymongo import MongoClient

def makeAggregate():
  print 'Making aggregation of commits..'

  commitsCollection = MongoClient("mongo-srv", 27017).gt.commits
  rankingCollection = MongoClient("mongo-srv", 27017).gt.commitsRanking

  pipe = [{'$unwind': '$commits'},{'$group':{"_id":"$_id", "picture": {"$first": "$picture"},'a':{'$sum':'$commits.a'},'d':{'$sum':'$commits.d'},'c':{'$sum':'$commits.c'}}}]
  cursor = commitsCollection.aggregate(pipeline=pipe)

  obj = next(cursor, None)
  while obj:
    rankingCollection.save(obj)
    obj = next(cursor, None)

makeAggregate()

代码在我的计算机上正常工作,但是当我将脚本移动到服务器时,脚本失败了,说:

Traceback (most recent call last):
  File "aggregate.py", line 17, in <module>
    makeAggregate()
  File "aggregate.py", line 12, in makeAggregate
    obj = next(cursor, None)
TypeError: dict object is not an iterator

命令python --version返回

在我的电脑上: Python 2.7.3

在服务器上 Python 2.7.6

命令pip show pymongo返回

在我的电脑上:

Usage: pip COMMAND [OPTIONS]
pip: error: No command by the name pip show
  (maybe you meant "pip install show")

(执行pip install show但在运行show时仍然这样说。)

在服务器上:

Name: pymongo
Version: 2.7
Location: /usr/local/lib/python2.7/dist-packages/pymongo-2.7-py2.7-linux-x86_64.egg
Requires:

在python中运行pymongo.version给了我:

在我的电脑中: 3.0

在服务器中 2.7

也许我必须更新这个?我怎么能这样做?

1 个答案:

答案 0 :(得分:8)

是的,这就是问题,不同版本的Pymongo for Development and Production environment

PyMongo 2.7 中,它返回:字典

    import java.util.Scanner;
    public class MinMax
    {

    public static void main(String[] args)
    {
        Scanner kb = new Scanner(System.in);
        int [] numbers = new int[5];
        int max = numbers[0]; 
        int min = numbers[0];

        for (int i = 0; i < numbers.length; i++)
        {
            System.out.println("Enter your next number:");
            numbers[i] = kb.nextInt();
            if (numbers[i] > max)
            {
                max = numbers[i];
            }
            if (min > numbers[i])
            {
                min = numbers[i];
            }
        }

        System.out.println("The maximum value in your array is " + max);
        System.out.println("The minimum value in your array is " + min);
    }

}

然而在 PyMongo 3.0 中,它返回:光标对象

{u'ok': 1.0, u'result': [{u'count': 3, u'_id': u'cat'}, {u'count': 2, u'_id': u'dog'}, {u'count': 1, u'_id': u'mouse'}]}

Refer Pymongo 2.7 Documentation
 Refer Pymongo 3.0 Documentation
 Changes made from PyMongo 2.7 to PyMongo 3.0

专业提示: 使用Virtual Environment for Python并创建一个需求文本文件。因为您可以安装相同版本的Python库及其在本地开发和生产中的依赖关系。

Refer Virtual Environment Python Package