aggregation framework - mongodb - filter out some values when doing $unwind -
i have following customer order data in mongodb
"_id" : 7, "customer name" : "john smith", "orderitem" : [ { "product_category" : "mobile", "price" : 900 }, { "product_category" : "computer", "price" : 4200.48 }, { "product_category" : "tv", "price" : 670.20 }, { "product_category" : "tv", "price" : 960.52 } ]
i need average each product category this:
"_id" : 7, "customer name" : "john smith", "orderitem" : [ { "product_category" : "mobile", "price" : 900 }, { "product_category" : "computer", "price" : 4200.48 }, { "product_category" : "tv", "price" : 815.36 } ]
i tried use $unwind not sure how group them . ?
use aggregation framework pipeline consists of following stages: $match
operation in first pipeline stage filters document stream allow matching documents (document _id = 7
in case) pass unmodified next pipeline stage, $unwind
operation. deconstructs desired orderitem
array field input documents output document each element can group on , aggregation operation of finding average of category prices. next stage in pipeline $group operation groups input documents product_category
, applies $avg
expression each group on price
. last stage $project
reshapes each document in stream produce desired outcome. aggregation like:
db.collection.aggregate([ { "$match": {"_id": 7} }, { "$unwind": "$orderitem" }, { "$group": { "_id": "$orderitem.product_category", "average_price": { "$avg": "$orderitem.price" } } }, { "$project": { "_id": 0, "product_category" : "$_id", "average_price": 1 } } ])
result:
{ "result" : [ { "average_price" : 4200.48, "product_category" : "computer" }, { "average_price" : 815.36, "product_category" : "tv" }, { "average_price" : 900, "product_category" : "mobile" } ], "ok" : 1 }
Comments
Post a Comment