Get a list of all unique tags in mongodb

后端 未结 2 1949
耶瑟儿~
耶瑟儿~ 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: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 }
    

提交回复
热议问题