如何通过python脚本运行mongo db查询?

时间:2015-09-21 06:59:35

标签: python django mongodb

我有两个mongo db查询

首先是:

 db.sale_order.find().forEach(function(doc){doc.orderDate = new 
        Date(doc.orderDate);db.sale_order.save(doc);})

,第二是:

db.sale_order.aggregate({$group: { _id: {year : { $year : "$orderDate" }, month : {$month : "$orderDate"},day :{ $dayOfMonth : "$orderDate"},},price : {$sum: "$price"}}} )

第二个查询仅在运行第一个查询后才起作用,之后使用python执行其他操作。

所以运行这两个查询,我使用以下代码:

def create_demo_accounts():
    Account.objects.all().delete()
    client = MongoClient('localhost', 27017)
    db = client['mydb']
    collection = db['sale_order']

    #collection.find().forEach(function(doc){doc.orderDate = new Date(doc.orderDate);db.sale_order.save(doc);})
    for doc in collection.find():
      doc['orderDate'] = Date(doc['orderDate'])  # line 127
      db.sale_order.save(doc) 
    try:
        for post in collection.aggregate({$group: { _id: {year : { $year : "$orderDate" }, month : {$month : "$orderDate"},day :{ $dayOfMonth : "$orderDate"},},price : {$sum: "$price"}}} ):   # line 130
          oid = post['_id']
          try:
            year = post['year']
            month = post['month']
            day = post['dayOfMonth']
            price = post['price']
            Account.objects.create(days = day, sales=price,
                                 expenses=400, ceo="Welch")
          except:
            pass
    except:
      pass

然后它出现以下错误:

SyntaxError at /
invalid syntax (utils.py, line 130)
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 1.8.4
Exception Type: SyntaxError
Exception Value:    
invalid syntax (utils.py, line 130)
Exception Location: /home/shubham/Music/Progress/django-graphos-master/demo_project/demo/views.py in <module>, line 12
Python Executable:  /usr/bin/python
Python Version: 2.7.6
Python Path:    
['/home/shubham/Music/Progress/django-graphos-master/demo_project',
 '/usr/local/lib/python2.7/dist-packages/mango-0.1-py2.7.egg',
 '/usr/local/lib/python2.7/dist-packages/django_mongo_auth-0.1.2-py2.7.egg',
 '/usr/local/lib/python2.7/dist-packages/django_mongoengine-0.1.1-py2.7.egg',
 '/usr/local/lib/python2.7/dist-packages/django_graphos-0.0.2a0-py2.7.egg',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PILcompat',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
 '/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
 '/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode']
Server time:    Mon, 21 Sep 2015 12:26:15 +0530

2 个答案:

答案 0 :(得分:0)

collection.aggregate电话中指定pipelineoptions时,您需要使用引号

collection.aggregate({'$group': { '_id': {'year' : { '$year' : "$orderDate" }, 'month' : {'$month' : "$orderDate"},'day' :{ '$dayOfMonth' : "$orderDate"},},'price' : {'$sum': "$price"}}})

此外,您无法在python中直接使用mongodb Date构造函数。您可以改为使用bson.Code 来传递Python中的javascript代码。

import bson # import bson library
# pass the javascript code string in bson 'Code' object
collection.find().forEach(bson.Code("function(doc){doc.orderDate = new Date(doc.orderDate);db.sale_order.save(doc);}"))

答案 1 :(得分:0)

您可以使用pymongo的db.eval功能。您的查询:

db.getCollection('test').update({filter},{update})

使用pymongo你可以这样做:

db.eval("db.getCollection('test').update({filter},{update})")