0

I have only experience with RDBS. There is it possible to aggregate fields by more than one field.

t_example:

country  |  city   |   val  |  useless
---------------------------------------
Ger      |  Ber    |    10  |    abc
Ger      |  Ber    |    10  |    abc
Ger      |  MU     |    10  |    abc
FR       |  Par    |    10  |    abc

SELECT country,city,sum(val) FROM t_example GROUP BY country,city;

=>

country  |  city   |   val  
----------------------------
Ger      |  Ber    |    20  
Ger      |  MU     |    10  
FR       |  Par    |    10  

Is it possible to get the same result by MongoDB if a collection contains the same Values on JSON files? I tried this on NodeJS:

dbs.collection('t_example').aggregate([{ $group: { "_id": "$country","count":{$sum:1}}}]).toArray(function(error,result){
            res.json(result);       
        });

I got a similiar result:

[{"_id":"Ger","count":30},{"_id":"Fr","count":10}]

Is it possible to break down the data by an additional field (city)? I also can´t change the key (_id). Otherwise the result is an empty Array.

1
  • 1
    _id takes document. Try _id:{country:"$country", city:"$city"} Commented Jan 6, 2018 at 16:53

1 Answer 1

1

You can use the following pipeline.

[
  { $group: { 
    _id: { country: "$country", city: "$city" }, 
    val: { $sum: "$val" } 
  } }
]

In fact, for a group stage, _id can be a structured object.

The resulting documents look like this.

[
    {
        "_id" : {
            "country" : "Fr",
            "city" : "Par"
        },
        "val" : 10.0
    },
    {
        "_id" : {
            "country" : "Ger",
            "city" : "MU"
        },
        "val" : 10.0
    },
    {
        "_id" : {
            "country" : "Ger",
            "city" : "Ber"
        },
        "val" : 20.0
    }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.