MongoDB和Python ::为什么$ group丢弃语法错误?
我是MongoDB的完整初学者,我希望有一个简单的问题,即如何在mongodb/python脚本中使用$ group
命令:
假设我有一个装有1000s的mongodb实例JSON文件。所有文档匹配此格式:
{
"data1": "some data here",
"moredata":
{
"data2": "more data here"
...etc...
}
}
我正在尝试使用$ group
进行组,然后通过data1
来计数所有文档,然后moredata.data2
。这是我的python代码:
db.collection.aggregate([
{
$group:{
_id: {data1: "$data1", data2: "$moredata.data2"},
count: {'$sum': 1}
}
}
])
运行上面的代码产生语法错误:
me@ubuntu/home/me$ /usr/bin/python3 test01.py
File "test03.py", line 68
$group:{
^
SyntaxError: invalid syntax
me@ubuntu/home/me$
SyntaxError:无效的语法
不是很有帮助的反馈,Google搜索[Python MongoDB $ group syntax rorror]
遍布整个地图。然后我记得,有时它有助于用引号中的$
封装变量。因此,要打破,我尝试了这种变化(仅在第3行上进行更改):
db.collection.aggregate([
{
'$group':{
_id: {data1: "$data1", data2: "$moredata.data2"},
count: {'$sum': 1}
}
}
])
现在脚本运行...但是引发了追踪:
Traceback (most recent call last):
File "test01.py", line 10
_id: {data1: "$data1", data2: "$moredata.data2"},
NameError: name '_id' is not defined
根据 mongodb文档,$ group
命令,_id
field offer因此,我敢打赌,将$ group
放入引号中实际上意味着我没有调用该功能/方法。我的直觉是,第一个版本的代码($ group
,而不是'$ group'
)是正确的。但是我在句法上做错了什么?谢谢。
I'm a complete beginner to MongoDB and have what I hope is a simple question about how to use the $group
command in a MongoDB/python script:
Suppose I have a MongoDB instance, loaded with 1000s of JSON documents. All documents match this format:
{
"data1": "some data here",
"moredata":
{
"data2": "more data here"
...etc...
}
}
I'm trying to use $group
to group and then count all the docs by data1
and then moredata.data2
. Here's my python code:
db.collection.aggregate([
{
$group:{
_id: {data1: "$data1", data2: "$moredata.data2"},
count: {'$sum': 1}
}
}
])
Running the above code produces a syntax error:
me@ubuntu/home/me$ /usr/bin/python3 test01.py
File "test03.py", line 68
$group:{
^
SyntaxError: invalid syntax
me@ubuntu/home/me$
SyntaxError: invalid syntax
isn't very helpful feedback, and Google searches on [python mongodb $group syntax error]
have been all over the map. Then I remembered that sometimes it helps enclosing variables with $
in quotes. So, going for broke, I tried this variation (change on line 3 only):
db.collection.aggregate([
{
'$group':{
_id: {data1: "$data1", data2: "$moredata.data2"},
count: {'$sum': 1}
}
}
])
Now the script runs... but throws a Traceback:
Traceback (most recent call last):
File "test01.py", line 10
_id: {data1: "$data1", data2: "$moredata.data2"},
NameError: name '_id' is not defined
According to the MongoDB documentation, the _id
field is required for the $group
command, so I'm betting that putting $group
in quotes actually means I'm not calling that function/method. My gut instinct is that the first version of code ($group
, not '$group'
) is correct. But what am I doing wrong syntactically? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论