繁体   English   中英

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

[英]mongodb query child collection count in aggregate group

我有一个mongo新手问题

我有一个汽车集合,其中有一个功能数组,我正尝试按品牌对汽车进行分组-并汇总该品牌的所有功能

这是一个类比,因为我正在研究的是具有类似问题的金融应用程序,所以

集合中包含以下文档:

/* 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那样工作,仅计算每个项目分组建议的功能?

我想你可以通过第一组makesum的长度features ,是这样的:

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

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

])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM