[英]Querying arrays in nested dictionary using mongoDB and pymongo
I have a dictionary like this:我有一本这样的字典:
dici = {
"city": {
"coord": {
"lat": 123123123,
"lon": 123123
},
"country": "asdsd",
"id": 2735943,
"name": "qweqwe",
"population": 249633,
"sunrise": 1617689349,
"sunset": 1617735844,
"timezone": 3600
},
"cnt": 40,
"cod": "200",
"list": [
{
"clouds": {
"all": 0
},
"dt": 1617721200,
"dt_txt": "2021-04-06 15:00:00",
"main": {
"feels_like": 17.87,
"grnd_level": 1002,
"humidity": 65,
"pressure": 1014,
"sea_level": 1014,
"temp": 18.29,
"temp_kf": 0.25,
"temp_max": 18.29,
"temp_min": 18.04
},
"pop": 0,
"sys": {
"pod": "d"
},
"visibility": 10000,
"weather": [
{
"description": "clear sky",
"icon": "01d",
"id": 800,
"main": "Clear"
}
],
"wind": {
"deg": 299,
"speed": 3.36
}
},
{
"clouds": {
"all": 16
},
"dt": 1617732000,
"dt_txt": "2021-04-06 18:00:00",
"main": {
"feels_like": 15.78,
"grnd_level": 1001,
"humidity": 63,
"pressure": 1013,
"sea_level": 1013,
"temp": 16.44,
"temp_kf": 0.58,
"temp_max": 16.44,
"temp_min": 15.86
},
"pop": 0,
"sys": {
"pod": "d"
},
"visibility": 10000,
"weather": [
{
"description": "few clouds",
"icon": "02d",
"id": 801,
"main": "Clouds"
}
],
"wind": {
"deg": 295,
"speed": 2.21
}
}
]
}`
And I would like to extract the entries of the array list when for example temp_max is greater than 16. What I have been doing is the following:当例如temp_max大于 16 时,我想提取数组列表的条目。我一直在做的事情如下:
unwind = db.forecast.aggregate([
{"$unwind": "$list"},
{"$project":{"list.dt_txt":1,
"list.main.temp":1,
"list.main.temp_max":1,
"list.main.temp_min":1}},
{"$match":{"list.main.temp_max":{"$gt":10}}
}
])
a = db.forecast.aggregate([
{"$match":
{"list.main[*].temp_max": {"$gt": 10}}}
])
b = db.forecast.find({"list.main.temp_max":{"$gt":16}})
But all of them get errors in the syntax, I can't seem to find the right syntax to access the temp_max key.但是它们都在语法中出现错误,我似乎找不到正确的语法来访问 temp_max 键。 Anyone can help me?任何人都可以帮助我吗? Thanks!谢谢!
You were close with the first query;您与第一个查询很接近; this should work:这应该工作:
unwind = db.forecast.aggregate([
{"$unwind": "$list"},
{"$match": {"list.main.temp_max": {"$gt": 16}}},
{"$project": {"list.dt_txt": 1, "list.main.temp": 1,
"list.main.temp_max": 1, "list.main.temp_min": 1, '_id': 0}}
])
Alternatively a find would work but only matches on the first list item, so the aggregate query is likely better.或者,查找会起作用,但只匹配第一个列表项,因此聚合查询可能会更好。
b = db.forecast.find({"list.main.temp_max": {"$gt": 16}}, {'list.main.$': 1, '_id': 0})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.