例如,我查询的MongoDB中的文档可以简化为以下内容:
{
"date":"2019-08-15",
"status":"5345",
"foo":
{
"bar":
{
"years":
{
"2018":
{
"const":1234
},
"2019":
{
"const":4321
}
}
}
}
}我正在尝试使用pyMongo从这个文档中获取"const“值。
“年份”中的关键字随文档的“日期”而变化。
我尝试使用此管道,尝试使用年份"date“从今年获取"const”:
pipeline=[
{'$match':{'status':{'$exists': True}}},
{'$project':
'const_thisYear':{
'$let':{
'vars':{
'yr':{ '$year': {'$convert':{'input': '$date','to': 'date'}}},
'res': '$foo.bar.years'
},
'in': '$$res.$$yr.const'
}
}
}
]在聚合时,我得到以下python异常:
OperationFailure: FieldPath field names may not start with '$'.我怎样才能正确地做到这一点?
Python 3.7.7
发布于 2021-01-03 00:03:02
您应该修改您的集合结构,使其不以键的形式存储数据;但不管怎样,只要使用常规的python dict操作就可以让您走出困境:
for doc in db.mycollection.find({'status': {'$exists': True}}, {'foo.bar.years': 1}):
for year, year_value in doc['foo']['bar']['years'].items():
print(year, year_value.get('const'))https://stackoverflow.com/questions/65539776
复制相似问题