I am using Mongo aggregate framework, suppose if i am having collection structure like this
[
{
_id: 123,
name: "john",
age: 30,
fruit: "apple",
},
{
_id: 345,
name: "moore",
age: 45,
fruit: "mango",
},
{
_id: 545,
name: "carl",
age: 30,
fruit: "grape",
},
{
_id: 96,
name: "shelby",
age: 25,
fruit: "apple",
},
{
_id: 86,
name: "loris",
age: 48,
fruit: "mango",
},
{
_id: 76,
name: "carl",
age: 55,
fruit: "grape"
}
]
I want to query and create a pipeline such that it return the count of particular fruit which lie under the duration which $bucket boudaries have created: for example result should look like this…
[
{
"_id": Specific_Boudary,
"userCount": Number_Of_Users_Lie,
"fruitsLie": [
{fruit_names_of_user_in_this_boundaries : fruit_counts},
]
},
{
"_id": 0,
"userCount": 3,
"fruitsLie": [
{apple: 2},
{grape: 1}
]
},
{
"_id": 40,
"userCount": 2,
"fruitsLie": [
{mango: 2}
]
},
{
"_id": "more than 50",
"userCount": 1,
"fruitsLie": [
{grape: 1}
]
}
]
so under age 30 we have 3 users, in which 2 eats apple and 1 eats grape so fruitsLie
field is responsible for this calculation.
how many approaches we can have to achieve the solution for this problem with specific $bucket boudaries and please explain thoroughly each stage, I am new to aggregate and currently learning…