After trying this solution and getting one step further i have another question regarding mongodb.
My question is:
How can i sort the output of:
doc = {_id : 16, days : { 1 : 123, 2 : 129, 3 : 140, 4 : 56, 5 : 57, 6 : 69, 7 : 80 }};
db.so.insert(doc);
map = function() {
emit(this._id, this.days["1"]);
emit(this._id, this.days["3"]);
emit(this._id, this.days["7"]);
}
reduce = function (k, vals) {
var sum = 0;
vals.forEach(function (v) {sum += v;});
return sum;
}
res = db.so.mapReduce(map, reduce, {out : {inline : 1}});
res.find();
The Output is like this:
"results" : [
{
"_id" : 16,
"value" : 225
},
{
"_id" : 33,
"value" : 230
},
{
"_id" : 302,
"value" : 274
}
]
Now i want to sort the result with:
res.find().sort({ "results.value":-1 });
which results in this error:
Sat Mar 31 01:15:45 TypeError: res.find().sort({'results.value':-1}) is not a function (shell):1
Does anybody can help me ?
Map-reduce operations take the documents of a single collection as the input and can perform any arbitrary sorting and limiting before beginning the map stage. mapReduce can return the results of a map-reduce operation as a document, or may write the results to collections.
Map-reduce is a common pattern when working with Big Data – it's a way to extract info from a huge dataset. But now, starting with version 2.2, MongoDB includes a new feature called Aggregation framework. Functionality-wise, Aggregation is equivalent to map-reduce but, on paper, it promises to be much faster.
The map function may optionally call emit(key,value) any number of times to create an output document associating key with value .
The main reason for the weak performance of mongos map-reduce is that it's javascript engine SpiderMonkey.
Here's an example of the same query using the MongoDB 2.2 Aggregation Framework:
db.so.aggregate(
{ $project : {
'_id' : 1,
'value' : { $add : ["$days.1","$days.3","$days.7"] },
}},
{ $sort: { 'value': -1 }}
)
.. and the output:
{
"result" : [
{
"_id" : 302,
"value" : 274
},
{
"_id" : 33,
"value" : 230
},
{
"_id" : 16,
"value" : 225
}
],
"ok" : 1
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With