mongodb查询聚合组中的子集合计数

时间:2018-04-19 09:59:31

标签: mongodb mongodb-query

我有一个mongo新手问题

我有一个汽车系列,它有一个功能阵列 我正在尝试通过make对汽车进行分组 - 并总结所有功能

这是一个类比,因为我正在处理的是具有类似问题的财务应用程序,所以

在集合中包含以下文件:

/* 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"
    ]
}

我想通过make对汽车进行分组,并计算所有零件

db.getCollection('cars').aggregate([
{
    $match : 
    { 
        $or : [{ make : "toyota"}, { make : "mazda"}]
    }       
},

{
  $group: { _id: '$make', count: { $sum: { $count : "$features" } } },
}

])

我无法以这种方式获得$ count,只计算每个分组项目的功能 建议?

1 个答案:

答案 0 :(得分:1)

我认为您可以先按make分组,sum features的长度,如下所示:

db.getCollection('myCollection').aggregate([

   { "$group": { "_id": "$make", "count": { "$sum": { "$size": "$features" } } } }

])