mongodb查询聚合组中的子集合计数
我有一个mongo新手问题 我有一个汽车系列,它有一个功能阵列 我正试图按品牌对汽车进行分组,并总结该品牌的所有功能 这是一个类比,因为我正在研究的是一个具有类似问题的金融应用程序,所以 收藏下列文件:mongodb查询聚合组中的子集合计数,mongodb,mongodb-query,Mongodb,Mongodb Query,我有一个mongo新手问题 我有一个汽车系列,它有一个功能阵列 我正试图按品牌对汽车进行分组,并总结该品牌的所有功能 这是一个类比,因为我正在研究的是一个具有类似问题的金融应用程序,所以 收藏下列文件: /* 1 */ { "_id" : ObjectId("5ad870ed22b6ac63f3b66359"), "make" : "toyota", "model" : "corolla", "year" : 1992, "type" : "sedan",
/* 1 */
{
"_id" : ObjectId("5ad870ed22b6ac63f3b66359"),
"make" : "toyota",
"model" : "corolla",
"year" : 1992,
"type" : "sedan",
"features" : []
}
/* 2 */
{
"_id" : ObjectId("5ad8712222b6ac63f3b66367"),
"make" : "toyota",
"model" : "camry",
"year" : 2014,
"type" : "sedan",
"features" : [
"cruise control",
"air conditioning",
"auto headlights"
]
}
/* 3 */
{
"_id" : ObjectId("5ad8714122b6ac63f3b6636c"),
"make" : "toyota",
"model" : "celica",
"year" : 2003,
"type" : "sports hatch",
"features" : [
"cruise control",
"air conditioning",
"turbo"
]
}
/* 4 */
{
"_id" : ObjectId("5ad8733722b6ac63f3b663a9"),
"make" : "mazda",
"model" : "323",
"year" : 1998,
"type" : "sports hatch",
"features" : [
"powered windows",
"air conditioning"
]
}
/* 5 */
{
"_id" : ObjectId("5ad8738022b6ac63f3b663af"),
"make" : "mazda",
"model" : "3",
"year" : 2014,
"type" : "sports hatch",
"features" : [
"powered windows",
"air conditioning",
"cruise control",
"navigation"
]
}
/* 6 */
{
"_id" : ObjectId("5ad873b322b6ac63f3b663b6"),
"make" : "mazda",
"model" : "cx9",
"year" : 2012,
"type" : "sports utility vehicle",
"features" : [
"powered windows",
"air conditioning",
"cruise control",
"navigation",
"4 wheel drive",
"traction control"
]
}
我想把汽车按品牌分类,并清点所有的零件
db.getCollection('cars').aggregate([
{
$match :
{
$or : [{ make : "toyota"}, { make : "mazda"}]
}
},
{
$group: { _id: '$make', count: { $sum: { $count : "$features" } } },
}
])
我不能让$count以这种方式工作,只计算每个分组项目的功能
建议?我想你可以先按
make
,sum
对功能的长度进行分组,如下所示:
db.getCollection('myCollection').aggregate([
{ "$group": { "_id": "$make", "count": { "$sum": { "$size": "$features" } } } }
])
为了更好地理解,请发布数据集。