为什么我的PyMongo查询中出现无效错误

时间:2018-12-04 20:52:22

标签: python django mongodb pymongo

我正在编写一个pymongo查询,当我在MongoDB GUI中编写该查询时它可以工作,但始终出现SyntaxError: invalid syntax错误。

我在做什么错了?

def get_codes(request):
   get_code = newsCode.aggregate([{
    '$match': {
        'site': { 
            '$exists': true 
        },
        'segment': {
            '$exists': true
        }
   }, {
    '$group': {
        '_id': {
            'site': "$site",
            'seg_code': {
                '$substr': ["$segment", 0, 4]
            },
            'segment': "$segment"
        }
    }
   }, {
    '$project': {
        'site': "$_id.site",
        'seg_code': "$_id.seg_code",
        'segment': "$_id.segment"
    }
   }, {
    '$sort': {
        '_id': 1
    }
   }
  }])

我的错误显示在

附近的,
 }, {
  '$project

跟踪:

Traceback (most recent call last):
File "/Users/userName/anaconda3/envs/env_dp_36/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/Users/userName/anaconda3/envs/env_dp_36/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run
self.check(display_num_errors=True)
File "/Users/userName/anaconda3/envs/env_dp_36/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "/Users/userName/anaconda3/envs/env_dp_36/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "/Users/userName/anaconda3/envs/env_dp_36/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "/Users/userName/anaconda3/envs/env_dp_36/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "/Users/userName/anaconda3/envs/env_dp_36/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "/Users/userName/anaconda3/envs/env_dp_36/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/userName/anaconda3/envs/env_dp_36/lib/python3.6/site-packages/django/urls/resolvers.py", line 540, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Users/userName/anaconda3/envs/env_dp_36/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/userName/anaconda3/envs/env_dp_36/lib/python3.6/site-packages/django/urls/resolvers.py", line 533, in urlconf_module
return import_module(self.urlconf_name)
File "/Users/userName/anaconda3/envs/env_dp_36/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "/Users/userName/Desktop/Dash/dash/dash/urls.py", line 3, in <module>
from . import views
File "/Users/userName/Desktop/Dash/dash/dash/views.py", line 5, in <module>
from .datamanager import *
File "/Users/userName/Desktop/Dash/dash/dash/datamanager.py", line 471
}, {
 ^
SyntaxError: invalid syntax

为什么会出现此错误?就像我说的那样,当我在GUI中执行此操作时,它就起作用了。我的语法有问题吗? PyMongo代码是否应该与MongoDB代码不同?

请帮助!

1 个答案:

答案 0 :(得分:1)

欢迎使用StackOverflow!

这里发生了几件事:

1)使用pymongo时,您是用python编写的,因此必须将true更改为True

2)当您尝试将这些查询聚合在一起时,aggregation函数接受代表查询一部分的字典列表。您发布的代码段将列表传递到函数中,其中第一个条目是包含您的$match$group键的部分,但是$project键发生在该字典已被关闭之前上一行的大括号。我不确定为什么在pymongo shell中不会抛出错误,因为肯定存在括号不匹配的情况,而mongo对此都不满意。

我在下面的代码段中清理了括号的对齐方式,尽管我不确定在应用程序上下文中运行查询时是否还会有其他问题。

def get_codes(request):
    get_code = newsCode.aggregate([
        {'$match': {'site': {'$exists': true}, 'segment': {'$exists': true}}},
        {'$group': {
            '_id': {
                'site': "$site",
                'seg_code': {'$substr': ["$segment", 0, 4]},
                'segment': "$segment"
            },
        }},
        {'$project': {
            'site': "$_id.site",
            'seg_code': "$_id.seg_code",
            'segment': "$_id.segment"
        }},
        {'$sort': {'_id': 1}},
    ])

最后一点:pymongo中的排序与编写原始mongo查询时的排序不同。参考: How to sort mongodb with pymongo