【发布时间】:2014-01-22 00:54:28
【问题描述】:
我在mongoose/mongodb中实现了一个简单的消息系统,架构如下
var schema = new mongoose.Schema({
user: {type:String, required:true},
updated: {type:Date, default:new Date()},
msgs: [ {m:String, // message itself
d:Date, // date of message
s: String, // message sender
r:Boolean // read or not
} ],
});
所有消息都存储在msg嵌套数组中,现在我想查询来自某个发件人的消息,例如,
{
"_id" : ObjectId("52c7cbe6d72ecb07f9bbc148"),
'user':'abc'
"msgs" : [{
"m" : "I want to meet you",
"d" : new Date("4/1/2014 08:52:54"),
"s" : "user1",
"r" : false,
"_id" : ObjectId("52c7cbe69d09f89025000005")
}, {
"m" : "I want to meet you",
"d" : new Date("4/1/2014 08:52:56"),
"s" : "user1",
"r" : false,
"_id" : ObjectId("52c7cbe89d09f89025000006")
}, {
"m" : "I want to meet you",
"d" : new Date("4/1/2014 08:52:58"),
"s" : "user2",
"r" : false,
"_id" : ObjectId("52c7cbea9d09f89025000007")
}
}
这里我有一个用户 'aa' 的文档,他有三条消息,两条消息来自'user1',一条消息来自'user2'。我想查询来自'user1'的消息
基本上有两种方法可以做到这一点,map-reduce 或聚合。 我尝试了 map-reduce 解决方案。
var o = {};
o.map = function() {
this.msgs.forEach(function(msg){
if(msg.s == person){ emit( msg.s, {m:msg.m,d:msg.d,r:msg.r}); }
})
}
o.reduce = function(key, values) {
var msgs = [];
for(var i=0;i<values.length;i++)
msgs.push(values[i]);
return JSON.stringify(msgs);
}
o.query = {user:'username'};
o.scope = {person:'user1'};
model.mapReduce(o,function (err, data, stats) {
console.log('map reduce took %d ms', stats.processtime)
if(err) callback(err);
else callback(null,data);
})
最终,它适用于类似的结果
[
{ _id: 'helxsz',
value: '[
{"m":"I want to meet you","d":"2014-01-04T08:52:54.112Z","r":false}, ....
]
]
结果是我想要的,但是格式有点复杂。 如何更改以使输出格式像这样
{ sender: 'helxsz',
messages: '[
{"m":"I want to meet you","d":"2014-01-04T08:52:54.112Z","r":false}, ...
]
}
以及我如何对结果进行排序和限制,所以我必须手动执行reduce函数?
最后一个 map reduce 方法需要 28 ms 来查询结果,为了模拟,我的集合有三个文档,每个文档都有一个 msg 数组,包含 4 个子文档。对我来说,28 毫秒对于查询来说有点太长了,是吗,现在我还索引了“用户”字段。
【问题讨论】:
标签: node.js mongodb mapreduce mongoose