from pymongo import MongoClient
# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database_name']
reviews_collection = db['reviews']
# 1. 查询出评分大于4分的所有评论
high_rated_reviews = reviews_collection.find({'rating': {'$gt': 4}})
for review in high_rated_reviews:
print(review)
# 2. 按照产品ID分组,计算每个产品的平均评分,并按照平均评分从高到低排序输出
pipeline = [
{
'$group': {
'_id': '$product_id',
'average_rating': {'$avg': '$rating'}
}
},
{
'$sort': {
'average_rating': -1
}
}
]
product_avg_ratings = reviews_collection.aggregate(pipeline)
for product in product_avg_ratings:
print(product)