node.js - Create Price Range in mongo with aggregation pipeline with Nodejs -
wan't create price range using mongodb aggregation pipeline.. while using elastic search or solr can directly price filter range value... how can create price range according products price, if there no product in range don't create 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 have create price range par product price filter available in flipkart or myntra using mongo aggregation...
[ { range : '100-200', count : 2 }, { range : '1200-2020', count : 3 }, { range : '3500-3900', count : 2 } ]
within aggregation framework pipeline, can take advantage of $cond
operator in $project
stage create field denotes range price falls in, , use $group
step 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)); });
Comments
Post a Comment