Danish
Danish

Reputation: 751

mongodb query child collection count in aggregate group

I have a mongo newbie question

I have a cars collection, that has a features array I'm trying to group cars by make - and sum all features for that make

this is an analogy, as what I'm working on is a financial application with a similar problem, so

Having the following documents in a collection:

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

I want to group the cars by make , and count all the parts

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

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

])

I can't get the $count to work that way, to just count the features for each item grouped suggestions ?

Upvotes: 1

Views: 1621

Answers (1)

Waqas
Waqas

Reputation: 6812

I think you can first group by make, sum the length of features, something like this:

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

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

])

Upvotes: 2

Related Questions