映射/缩小和排序嵌套文档 [英] Map/Reduce and Sort Nested Document
问题描述
我对mongodb中的Map/Reduce排序内部文档有疑问. 该方案如下:
I've got a question regarding Map/Reduce Sort an inner Document in mongodb. The scheme is like following:
{
"_id" : 16,
"days" : {
"1" : 123,
"2" : 129,
"3" : 140,
"4" : 56,
"5" : 57,
"6" : 69,
"7" : 80
}
所以我现在的问题是: 我如何才能根据上述数据总结某些特定的日子. 例如:
So my question now is: How can i achieve to sum some specific days from the above data. For an example:
我想对第1,3和7天的值求和,以得出结果. 我尝试了解决方案 基于文档外部包含的属性的MapReduce聚合,但是没有成功.
I want to sum the values of day 1,3 and 7 an get the result out of this. I tried the solution from MapReduce aggregation based on attributes contained outside of document but didn't had any success with it.
有人可以帮助我吗?
推荐答案
MapReduce是一个循环处理一堆文档并执行操作的操作.我不完全确定这正是您想要的,但是可能您发布的是实际问题的简单形式.在任何情况下,以下代码都可以通过将单个文档的_id用作reduce函数的键来发出3次,从而起作用.
MapReduce is an operation that loops over a bunch of documents and performs an operation. I'm not entirely sure it's exactly what you want, but possibly you're posting a simpler form of your real problem. In any case the following code works by emitting 3 times for your single document, using the _id of the document as the key to the reduce function.
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();
这篇关于映射/缩小和排序嵌套文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!