Get a list of all unique tags in mongodb

时光毁灭记忆、已成空白 提交于 2019-12-18 11:52:26

问题


I am beginning with mongodb and have a collection with documents that look like the following

{
    "type": 1,
    "tags": ["tag1", "tag2", "tag3"]
}
{
    "type": 2,
    "tags": ["tag2", "tag3"]
}
{
    "type": 3,
    "tags": ["tag1", "tag3"]
}
{
    "type": 1,
    "tags": ["tag1", "tag4"]
}

With this, I want a set of all the tags for a particular type. For example, for type 1, I want the set of tag1, tag2, tag3, tag4 (any order).

All I could think of is to get the tags and add them to a set in python, but I wanted to know if there is a way to do it with mongodb's mapreduce or something else. Please advise.


回答1:


If you just want a (distinct) list of the tags then using distinct will be best. Map/Reduce will be slower and can't use an index for the javascript part.

http://docs.mongodb.org/manual/reference/method/db.collection.distinct/

db.coll.distinct("tags", {type:1}) Will return a set of tags for type=1.




回答2:


You are right, a Map/Reduce might work for what you are trying to accomplish, but a Set might be faster and less code.

> m =     function() {
...         for (var tag in this.tags) {
...             emit(this.tags[tag], 1);
...         }
...     }

> r =     function(key, values) {
...         return 1;
...     }

> db.tags.mapReduce(m, r).find()
{ "_id" : "tag1", "value" : 1 }
{ "_id" : "tag2", "value" : 1 }
{ "_id" : "tag3", "value" : 1 }


来源:https://stackoverflow.com/questions/4976567/get-a-list-of-all-unique-tags-in-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!