Get a list of all unique tags in mongodb

后端 未结 2 1936
耶瑟儿~
耶瑟儿~ 2020-12-29 05:32

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

{
    \"type\": 1,
    \"tags\": [\"tag1\", \"tag2\", \"tag3\"]         


        
相关标签:
2条回答
  • 2020-12-29 06:08

    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.

    0 讨论(0)
  • 2020-12-29 06:28

    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 }
    
    0 讨论(0)
提交回复
热议问题