我已经在这个问题上挣扎了一段时间。我有州和度假屋的数据。我需要找到每种度假屋的数量,并返回具有最多和最少位置的属性类型。我已经能够按状态分组并计算数组中的属性数量。我只需要提取最多和最少的财产。
我手头的数据。
{'_id': 'CA', 'properties': [{'property_type': 'Camper/RV', 'quantity': 1}, {'property_type': 'Hostel', 'quantity': 2}, ...]}
{'_id': 'BR', 'properties': [{'property_type': 'Guest suite', 'quantity': 3}, {'property_type': 'Bed and breakfast', 'quantity': 7}, ...]}
...
我想写一个返回数据的查询,如下所示
{'_id': 'TR', 'most_type': 'Apartment', 'most_number': 53, 'least_type': 'Camper/RV', 'least_number': 5}
{'_id': 'CA', 'most_type': 'House', 'most_number': 53, 'least_type': 'TinyHouse', 'least_number': 3}
...
发布于 2021-03-14 15:51:55
您使用aggregate
db.collection.aggregate([
{
"$unwind": "$properties"
},
{
"$sort": {
"properties.quantity": -1
}
},
{
"$group": {
"_id": "$_id",
"most_type": {
"$first": "$properties.property_type"
},
"most_number": {
"$first": "$properties.quantity"
},
"least_type": {
"$last": "$properties.property_type"
},
"least_number": {
"$last": "$properties.quantity"
}
}
}
])
尝试一下here
https://stackoverflow.com/questions/66618278
复制相似问题