Suppose I have this following dataset,
//listings collection
{
"city": New York,
"beds": 2,
"build": concrete
}
{
"city": New York,
"beds": 4,
"build": wood
}
{
"city": New York,
"beds": 3,
"build": asphalt
}
{
"city": New York,
"beds": 1,
"build": concrete
}
I can get the number of following averages of beds with the following query
db.listings.aggregate(
[
{
$match: {
"city": "New York"
}
},
{
$group: {
"_id": null,
"Avg-Beds": {
$avg:"$beds
}
}
}
])
Which is cool, but what I'm really looking for is something like
{
"Avg-Beds": 2
"Build" {
"Asphalt" : 1,
"Wood": 1,
"Concrete": 2
}
In summary, I want to average the beds, but I want to count the output of "build" field at the same time.
How is this achievable with mongodb?
Even better would be something like an output of
"Build": {
"Asphalt": "25%"
}
Which would give a percentage based value. Note that I do not have a predefined set of "build" output fields.