问题描述
我一直在跟踪玩家的分数,以记录增长情况.我的架构如下:
I am keeping track of players' scores in order to record growth. My schema is as follows:
Schema = new schema({
pid: { type: Number }
, name: { type: String }
, alliance: {
aid: { type: Number }
, name: { type: String }
}
, city_cnt: { type: Number }
, score: { type: Number }
, rank: { type: Number }
, createdTimeAt: { type: Date, default: Date.now }
, createdDayAt: { type: Number, default: function() { return Math.floor(Date.now() / (24 * 60 * 60)) } }
})
现在我想每天为每位玩家拉出一条记录(这是该天的最后记录分数).所以我把这张图缩小了:
Now I want to pull out one record per day (being the last recorded score for that day) per player. So I have this map reduce:
growthMap = function(){
emit('createdTimeAt', this.createdTimeAt.toString())
}
growthReduce = function(prev, doc) {
if (doc.createdTimeAt > prev.createdTimeAt) {
prev.createdTimeAt = doc.createdTimeAt
prev.score = doc.score
prev.pid = doc.pid
prev.name = doc.name
}
}
mongoose.connect('mongodb://localhost/my_database')
mongoose.model('Players', Schema)
mongoose.connection.db.executeDbCommand({
mapreduce: 'players'
, map: growthMap.toString()
, reduce: growthReduce.toString()
, out: 'playerGrowth'
}, function(err, ret){
if (err) console.log(err)
else {
console.log(ret.documents)
mongoose.connection.db.collection('playerGrowths', function(err, collection){
collection.find({}).toArray(function(err, docs){
console.dir(docs)
})
})
}
})
地图缩小似乎可以正常工作.第一个输出 console.log(ret.documents)产生以下结果:
The map reduce seems to work fine. The first output console.log(ret.documents) produces this result:
[ { result: 'playerGrowth',
timeMillis: 11268,
counts: { input: 14635, emit: 14635, reduce: 15, output: 1 },
ok: 1 } ]
但是,每当我尝试在第二个输出 console.log(docs)中查询新集合时,都会得到一个没有结果的空数组.我确定我做错了什么,但是在mapreduce方面缺少猫鼬文档.
However, whenever I try to query the new collection in the second output console.log(docs), I get an empty array with no results. I'm sure I am doing something wrong, but the mongoose documentation is lacking when it comes to mapreduce.
根据下面Jed的回答,我将 mongoose.connection.db.collection('playerGrowths'更改为 mongoose.connection.db.collection('playerGrowth',然后我m至少从find({}).toArray()获得结果.但是,这仍然不是我期望或需要的...
As per Jed's answer below I changed mongoose.connection.db.collection('playerGrowths' to mongoose.connection.db.collection('playerGrowth' and I'm at least getting a result from the find({}).toArray(). However, it's still not what I'm expecting or need...
我的新结果
[ { result: 'playerGrowth',
timeMillis: 5743,
counts: { input: 14635, emit: 14635, reduce: 15, output: 1 },
ok: 1 } ]
null
[ { _id: 'createdTimeAt', value: null } ]
推荐答案
generate()函数应返回键/值对.由于您的键"是"createdTimeAt",因此其汇总结果.您可能应该这样做:
The emit() function should return a key-value pair. Since your "key" is "createdTimeAt", its what it aggregates results by. You should probably do:
emit(this.createdTimeAt.toString(), <your value>)
这篇关于猫鼬mapreduce()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!