我正在尝试使用Nodejs,mongoose和MongoDB来使用map reduce操作。 我有一个相当扁平的架构结构,我想得到每个'命名'对象的值/日期对列表。地图缩小功能显然有问题,但我看不出如何修复它以获得我想要的格式。
MongoDB文档架构如下:
{ "name" : "object1", "value" : "123", "date" : "2013-01-02 01:00:00" }
{ "name" : "object1", "value" : "456", "date" : "2013-01-02 02:00:00" }
{ "name" : "object2", "value" : "123", "date" : "2013-01-02 02:00:00" }
我在Mongoose Schema中使用的map reduce函数如下:
var o = {};
o.map = function () {
emit(
{ 'name': this.name },
{'data': [ { 'value': this.value, 'date': this.date} ] }
)
}
o.reduce = function (k, vals) {
var reduced = {'data': []};
for (var i in vals) {
reduced.data.push(vals[i]);
}
return reduced;
}
this.mapReduce(o, function(err, model) {
if(err) console.log(err);
model.find().exec(cb);
});
我希望看到的是
中的一些JSON[
{
"name": "object1",
"data": [
{
"value": "123",
"date": "2013-01-02T01:00:00.123456"
},
{
"value": "456",
"date": "2013-01-02T02:00:00.123456"
},
]
},
{
"name": "object2",
"data": [
{
"value": "123",
"date": "2013-04-22T13:10:03.893018"
},
...
]
},
...
但我最终得到了这个嵌套的混乱!有人能指点我错过的东西!!
[
{
"_id": {
"name": "object1"
},
"value": {
"data": [
{
"data": [
{
"data": [
{
"data": [
{
"value": "123",
"date": "2013-01-02T02:00:00.123456"
}
]
},
{
"data": [
{
"value": "465",
"date": "2013-01-02T01:00:00.123456"
}
]
},
... etc
答案 0 :(得分:0)
var o = {};
o.map = function () {
emit(this.name, { 'value': this.value, 'date': this.date} )
}
o.reduce = function (k, vals) {
var reduced = {name: k, data : []};
for (var i in vals) {
reduced.data.push(vals[i]);
}
return reduced;
// or just return vals? it's already the array you want.
}