Reputation: 1316
I have this collection in mongodb:
articles = {
{
id: 102
pagelinks: { 104, 105, 107, 108 },
title: "page1"
},
{
id: 104
pagelinks: { 102, 205, 207, 108 },
title: "page2"
},
...
}
I want to have this collection:
page_link_titles= {
{
id: 102,
links: { "page2", "page5", "page7", "page9"}
},
{
id: 104,
links: { "page1", "page5", "page7", "page9" }
},
...
}
I am using mapreduce in this way:
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'});
and I get this error:
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
Any suggestions?
Upvotes: 1
Views: 1511
Reputation: 103325
You can try this code snippet:
Sample collection:
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"
}
]);
The magic:
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);
});
The result:
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" ]
}
Upvotes: 1
Reputation: 1372
Upvotes: 2