简体   繁体   English

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

[英]how to run mongo db query via python script?

I have two mongo db query我有两个 mongo db 查询

first is:首先是:

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

and second is:其次是:

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

this second query is only work after running first query , after that performing other operation using python .第二个查询仅在运行第一个查询后才有效,然后使用 python 执行其他操作。

so running this two query , I am using following code :所以运行这两个查询,我使用以下代码:

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

then it is giving following error :然后它给出以下错误:

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

You can use pymongo's db.eval function.您可以使用 pymongo 的db.eval函数。
eg your query:例如您的查询:

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

using pymongo you can do like:使用 pymongo 你可以这样做:

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

You need to use quotes when specifying pipeline and options in collection.aggregate call:collection.aggregate调用中指定pipelineoptions时需要使用引号

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

Also, you can't directly use mongodb Date constructor in python .此外,您不能在 python 中直接使用 mongodb Date构造函数 You can instead use bson.Code to pass the javascript code in Python .您可以改为使用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);}"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM