我的MongoDB文档如下
{
"_id" : ObjectId("622126001b68d9136e48ba4a"),
"brand_name" : "Sony",
"brand_rating" : [
{
"cust_name" : "Amit K",
"rating" : 4
},
{
"cust_name" : "Raghu",
"rating" : 4
}
],
"models" : [
{
"model_name" : "Sony Xperia Z2",
"RAM" : "3GB",
"ROM" : "32GB",
"price" : 18000,
"buyer" : [
{
"cust_name" : "Amit K",
"rating" : 5
},
{
"cust_name" : "Raghu",
"rating" : 4
}
]
},
{
"model_name" : "Sony XP",
"RAM" : "4GB",
"ROM" : "64GB",
"price" : 25000,
"buyer" : [
{
"cust_name" : "Amit K",
"rating" : 5
},
{
"cust_name" : "Raghu",
"rating" : 4
}
]
}
]
}
我尝试以下两个查询:
> db.brand.distinct("brand_name")
输出:["索尼","三星","iPhone"]
db.brand.aggregate({$addFields : {total_rating : {$sum : "$brand_rating.rating"} }}, {$sort : {total_rating : -1}}, {$limit : 1 }, {$project : {_id : 0, brand_name : 1, total_rating : 1} })
输出:{"品牌名称":"iPhone","总评分":10}
我想在一个查询中获得两个输出(期望输出(
["索尼"、"三星"、"iPhone"]{"品牌名称":"iPhone";,"total_rating":10}
最简单的方法是什么?
正如@rickhg12hs所指出的,您可以使用$facet来获得以下内容:
{
"brand_set": [
"Sony"
],
"top_sum": {
"brand_name": "Sony",
"total_rating": 8
}
}
参见游乐场:https://mongoplayground.net/p/84NadbPpDbe