how to use mapreduce in mongoose/mongodb query subdocument?
I am not sure how efficient it is for you, but for formatting this will work like below I made custom key names title
, className
and start
which are not in the collection.So store the result of mapReduce in a new collection and retrive it. (if you are not going to run mapReduce on every single request)
db.events.aggregate([{ $project: { title: "$value", className: "$_id.method", start: "$_id.time", _id:0 } }])
If you use the map-reduce framework, which I do not recommend due to its performance, then you can use the finalize
function together with the map
and reduce
to reshape the final result or alternatively, rename the fields during in the emit functions.
Instead I recommend using the aggregation framework which has much better performance:
db.collection.aggregate([ {$match: {"user" : "user1"}}, {$project: {"_id": 0, "sender": "$user", "messages": "$msgs"}}])