[英]How to get sum of a particular field of a collection in MongoDB collection using PyMongo?
[英]How do I make a field path include a value in same document using MongoDB/pyMongo?
我查詢的 MongoDB 中的文檔可以簡化為以下示例:
{
"date":"2019-08-15",
"status":"5345",
"foo":
{
"bar":
{
"years":
{
"2018":
{
"const":1234
},
"2019":
{
"const":4321
}
}
}
}
}
我正在嘗試使用 pyMongo 從本文檔中獲取“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
您應該修改您的集合結構以不將數據存儲為鍵; 但無論如何,只需使用常規的 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'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.