0

我想在前端或来自数据库的视图页面收集相同的标签。标签正在列表中收集。

模型.py

class Note(Document):
    tags = db.ListField(db.StringField())

MongoDB数据示例:

"notes" : [ 
        {
            "title":"lipsum",
            "content":"lipsum",
            "tags" : [ 
                "python", 
                "OOP", 
                "mongoengine"
            ]
        }, 

        {
            "title":"lipsum2",
            "content":"lipsum2",
            "tags" : [ 
                "sql", 
                "functional", 
                "mongoengine",
                "python"
            ]
        }

如何从 jinja2、python、flask.ext 或 mongoengine 本身获得以下结果?

mongoengine 2
OOP
functional
python 2
sql

感谢您的建议。

4

1 回答 1

1

mongoengineQuerySet.distinctQuerySet.count函数可以在这里成为你的朋友:

tag_counts = {}
tag_names = Note.objects.distinct('tags')
for tag in tag_names:
    tag_counts [tag] = Note.objects(tags=tag).count()

或在一行中:

dict([(tag, Note.objects(tags=tag).count()) for tag in Note.objects.distinct('tags')])

这些都构成了这个字典:

{'OOP':1, 'mongoengine':2 ,'python': 2, 'functional':1, 'sql':1}
于 2016-01-27T14:11:52.800 回答