我在mongodb中有这个集合:
articles = {
{
id: 102
pagelinks: { 104, 105, 107, 108 },
title: "page1"
},
{
id: 104
pagelinks: { 102, 205, 207, 108 },
title: "page2"
},
...
}
我想要这个系列:
page_link_titles = {
{
id: 102,
links: { "page2", "page5", "page7", "page9"}
},
{
id: 104,
links: { "page1", "page5", "page7", "page9" }
},
...
}
我以这种方式使用mapreduce:
var map = function () {
var output= {links:db.articles.find({id : {$in: db.articles.findOne({id:this.id}).pagelinks}}, {title: 1, _id:0})}
emit(this.id, output);
};
var reduce = function(key, values) {
var outs={ links:null}
values.forEach(function(v){
if(outs.links ==null){
outs.links = v.links
}
});
return outs;
};
db.articles.mapReduce(map,reduce,{out:' page_link_titles'});
我收到此错误:
mapreduce failed: {
"errmsg" : "exception: ReferenceError: db is not defined near 't={links:db.articles.find({id: {$in: [d' (line2)",
"code" : 16722,
"ok" : 0
} at src/mongo/shell//collection.js:1224
有什么建议吗?
答案 0 :(得分:2)
答案 1 :(得分:1)
您可以尝试以下代码段:
样品采集:
db.articles.insert([
{
_id: 102,
pagelinks: [ 104, 105, 107, 108 ],
title: "page1"
},
{
_id: 104,
pagelinks: [ 102, 205, 207, 108 ],
title: "page2"
},
{
_id: 105,
pagelinks: [ 102, 205, 207, 104 ],
title: "page3"
},
{
_id: 107,
pagelinks: [ 105, 205, 207, 104 ],
title: "page3"
}
]);
神奇:
db.articles.find().forEach( function (doc){
var obj = {
"_id": doc._id
};
var links = [];
doc.pagelinks.forEach( function (x){
var result = db.articles.findOne({ "_id": x });
if(result && result.title) links.push(result.title);
});
obj["links"] = links.filter(function (value, index, self) {
return self.indexOf(value) === index;
});
db.page_link_titles.save(obj);
});
结果:
db.page_link_titles.find();
/* 1 */
{
"_id" : 102,
"links" : [ "page2", "page3" ]
}
/* 2 */
{
"_id" : 104,
"links" : [ "page1" ]
}
/* 3 */
{
"_id" : 105,
"links" : [ "page1", "page2" ]
}
/* 4 */
{
"_id" : 107,
"links" : [ "page3", "page2" ]
}