I am trying to figure out this map/reduce system in mongoDB. I have the following basic schema/layout in my collection.
{
_id: 1,
name: n1,
website: w1,
tags: [
myTag1,
myTag3
]
}
{
_id: 2,
name: n2,
website: w2,
tags: [
myTag2,
myTag3
]
}
{
_id: 3,
name: n3,
website: w3,
tags: [
myTag2,
myTag4
]
}
How can I retrieve an array of unique tags? I would like this to be returned to me for further use.
{
tags: [
myTag1,
myTag2,
myTag3,
myTag4
]
}
By the way this is what I have come up with, but it just returns the _id and tags of each item instead of combining the tags into a single object.
var map = function() {emit( this._id,{tags: this.tags});};
var reduce = function(key, values) {
var t = [];
values.forEach(function(doc) {
var tags = doc.tags;
tags.forEach(function(tag) {
if (!(tag in t)) {
t.push(tag);
}
});
});
return {tags: t};
};
var op = db.businesses.mapReduce(map, reduce, {out: "mr_results"});
db[op.result].find();
There’s no need to use map-reduce in your case. Just use the
distinctfunction:You can try it in the mongo shell:
Also, you should keep in mind that map/reduce in MongoDB is not suitable for real-time querying.