'MongoDB - Find how many documents have the same characteristics
I'm saying sorry for the title and for not providing an example, but I'm very new to MongoDB and, after trying to accomplish this result using MySQL, I moved to MongoDB because I think that can be simpler to archive this result :(
I'll need to find how many documents have the same "characteristics".
I try to expose this with a restaurant example: I need to find the most popular dishes that a family ordered
This is the dataset, where persons and withChildren is the criteria of the group by:
{"persons": 4, "dish1": 3, "dish2": 4},
{"persons": 4, "dish1": 3, "dish2": 4},
{"persons": 4, "dish1": 3, "dish2": 4},
{"persons": 4, "withChilden": true, "dish1": 3, "dish2": 4},
{"persons": 4, "dish1": 3, "dish2": 2},
{"persons": 4, "dish1": 3, "dish2": 2},
{"persons": 4, "dish1": 3, "dish2": 2, "dish3": 6},
I make a separation to the rows to better show the difference:
- (4 persons) has ordered (dish1=3 / dish2=4) three times
- (4 persons withChilden) has ordered (dish1=3 / dish2=4) one time
- (4 persons has ordered) has ordered (dish1=3 / dish2=2) two times
- (4 persons has ordered) has ordered (dish1=3 / dish2=2 / dish3=6) one time
The goal is to produce documents that expose the previous rows, like that:
{
{ "type": {"persons": 4} },
"dish1": 3,
"dish2": 4,
"tot": 3
}
For the type with children, will be:
{
{ "type": {"persons": 4, "withChildren": true} },
"dish1": 3,
"dish2": 4,
"tot": 1
}
I'll already try to read this solutions, that seems to be a little similar on what I need to accomplish, but because I'm very new to MongoDB I don't know if it's possible to have this result with a single query, if I need to write a script and so on.
The nested object in the result is not trivial, so the result could be a plain object too, like that:
{
"persons": 4,
"dish1": 3,
"dish2": 4,
"tot": 3
}
Thanks a lot for your help and understanding
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
