Hi'我正在编写一个使用MongoDB数据库的应用程序。我有一个用户集合,用于存储所有用户数据。文件具有以下形式:
{
"_id" : ObjectId("542e67e07f724fc2af28ba75"),
"id" : "",
"email" : "luigi@gmail.com",
"tags" : [
{
"tag" : "Paper Goods:Liners - Baking Cups",
"weight" : 2,
"lastInsert" : 1412327492874
},
{
"tag" : "Vegetable:Carrots - Jumbo",
"weight" : 4,
"lastInsert" : 1412597883569
},
{
"tag" : "Paper Goods:Lialberto- Baking Cups",
"weight" : 1,
"lastInsert" : 1412327548205
},
{
"tag" : "Fish:Swordfish Loin Portions",
"weight" : 3,
"lastInsert" : 1412597939124
},
{
"tag" : "Vegetable:Carrots - alberto@gmail.com",
"weight" : 2,
"lastInsert" : 1412597939124
}
]
}
现在我创建了一个recommendation.tagsMatch集合,用于存储两个标签之间的相似性。
收集的文件具有以下形式:
{
"_id" : "Fish:Swordfish Loin Portions-Paper Goods:Lialberto- Baking Cups",
"value" : {
"tag1" : "Fish:Swordfish Loin Portions",
"tag2" : "Paper Goods:Lialberto- Baking Cups",
"sum1" : 3,
"sum2" : 1,
"sumQ1" : 9,
"sumQ2" : 1,
"sumProd" : 3,
"count" : 2
}
}
现在我正在编写一个从recommendation.users
文档到recommendation.tagsMatch
文档的mapReduce。
如果是第一次映射文档,则value.count
字段必须为0,否则value.count
必须是相应recommendation.tagsMatch
文档中的旧值。
我已经实现了我的mapReduce功能如下:
var f1 = function() {
var rows = this.tags;
if (rows != undefined) {
rows = rows.sort(function(a, b){return a.tag > b.tag})
rows.forEach( function(rowThis) {
if (rows != undefined) {
/** prendo solo i maggiori di quello che sto confrontando */
var toCompare = rows.filter(function(e){return rowThis.tag < e.tag;})
toCompare.forEach( function(rowThat) {
var key = rowThis.tag + "-" + rowThat.tag;
var documentValue = db.recommendation.tagsMatch.find({_id: key}).one()
var countValue = 0
if(documentValue.value.count != undefined)
countValue = documentValue.value.count
var value = {
tag1: rowThis.tag,
tag2: rowThat.tag,
sum1: rowThis.weight,
sum2: rowThat.weight,
sumQ1: Math.pow(rowThis.weight, 2),
sumQ2: Math.pow(rowThat.weight, 2),
sumProd: rowThis.weight * rowThat.weight,
count: countValue
}
emit(key, value);
});
}
});
}
};
var r1 = function(key, values) {
var reducedObject = {
tag1: "",
tag2: "",
sum1: 0,
sum2: 0,
sumQ1: 0,
sumQ2: 0,
sumProd: 0,
count: 0
}
values.forEach( function(value) {
reducedObject.tag1 = value.tag1;
reducedObject.tag2 = value.tag2;
reducedObject.sum1 += value.sum1;
reducedObject.sum2 += value.sum2;
reducedObject.sumQ1 += value.sumQ1;
reducedObject.sumQ2 += value.sumQ2;
reducedObject.sumProd += value.sumProd;
reducedObject.count += value.count;
});
return reducedObject;
};
我将te mapReduce命令称为:
db.recommendation.users.mapReduce(f2, r1,{query: {}, "out": "recommendation.tagsMatch"}).
但是控制台给了我以下错误:
2014-10-27T17:01:28.923+0100 map reduce failed:{
"errmsg" : "exception: ReferenceError: db is not defined near 'ntValue = db.recommendation.tagsMatch.fin' (line 11)",
"code" : 16722,
"ok" : 0
}
怎么了??我该怎么解决??
使用mapReduce增量解决:http://docs.mongodb.org/manual/tutorial/perform-incremental-map-reduce/