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

Posted

技术标签:

【中文标题】为啥我的 PyMongo 查询中出现无效错误【英文标题】:Why am I getting invalid error in my PyMongo Query为什么我的 PyMongo 查询中出现无效错误 【发布时间】:2019-05-06 08:50:50 【问题描述】:

我正在编写一个 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 代码不同吗?

请帮忙!

【问题讨论】:

请显示回溯 @roganjosh,我刚刚做了 【参考方案1】:

欢迎来到 ***!

这里发生了几件事:

1) 使用 pymongo 时,你是用 python 编写的,所以 true 必须更改为 True

2) 当您尝试将这些查询聚合在一起时,聚合函数接受代表查询一部分的字典列表。您发布的 sn-p 将一个列表传递给函数,其中第一个条目是包含您的 $match$group 键的部分,但 $project 键发生在该字典被大括号关闭后上面的行。我不确定为什么这不会在 pymongo shell 中引发错误,因为肯定存在 mongo 不满意的括号不匹配。

我在下面的 sn-p 中清理了括号的对齐方式,但我不确定在应用程序上下文中运行查询时是否可能存在其他问题。

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

【讨论】:

太棒了!非常感谢!

以上是关于为啥我的 PyMongo 查询中出现无效错误的主要内容,如果未能解决你的问题,请参考以下文章

使用 flask_pymongo 时身份验证失败

React Element Type 无效,为啥会出现此错误,如何解决?

为啥当我的子查询无效时,此 SQL 查询会起作用? - 甲骨文 [重复]

我的一个 Oracle Apex 查询出现“无效标识符错误”

为啥我的 SQL 查询会出现内部服务器错误?

MongoDB pymongo模块