Reputation: 162
Wan't create Price range Using mongodb aggregation pipeline.. while using elastic search or solr we can directly get price filter range value... How can i create price range according to my products price, if there is no product in that range then don't create that range...
{
"_id" : ObjectId("5657412ddb70397479575d1d"),"price" : 1200
},
{
"_id" : ObjectId("5657412ddb70397479575d1d"),"price" : 200
},
{
"_id" : ObjectId("5657412ddb70397479575d1d"),"price" : 2000
},
{
"_id" : ObjectId("5657412ddb70397479575d1d"),"price" : 2020
},
{
"_id" : ObjectId("5657412ddb70397479575d1d"),"price" : 100
},
{
"_id" : ObjectId("5657412ddb70397479575d1d"),"price" : 3500
},
{
"_id" : ObjectId("5657412ddb70397479575d1d"),"price" : 3900
}
From above i have to create price range as par product price like filter available in flipkart OR myntra using Mongo aggregation...
[
{
range : '100-200',
count : 2
},
{
range : '1200-2020',
count : 3
},
{
range : '3500-3900',
count : 2
}
]
Upvotes: 1
Views: 1573
Reputation: 103445
Within the aggregation framework pipeline, you can take advantage of the $cond
operator in the $project
stage to create an extra field that denotes the range the price falls in, and then use the $group
step to get the counts:
var pipeline = [
{
"$project": {
"price": 1,
"range": {
"$cond": [
{
"$and": [
{ "$gte": ["$price", 100] },
{ "$lte": ["$price", 200] }
]
},
"100-200",
{
"$cond": [
{
"$and": [
{ "$gte": ["$price", 1200] },
{ "$lte": ["$price", 2020] }
]
},
"1200-2020", "2021-above"
]
}
]
}
}
},
{
"$group": {
"_id": "$range",
"count": { "$sum": 1 }
}
},
{
"$project": {
"_id": 0,
"range": "$_id",
"count": 1
}
}
];
collection.aggregate(pipeline, function (err, result){
if (err) {/* Handle err */};
console.log(JSON.stringify(result, null, 4));
});
Upvotes: 1