2011-01-06 54 views
4

我想弄清楚如何從存儲在MongoDB中的博客文章中獲取相關標籤的列表。列出存儲在MongoDB中的博客文章的相關標籤

數據結構

{ 
    title: "Post #1", 
    tags: { "news", "politics" } 
}, 
{ 
    title: "Post #2", 
    tags: { "news", "entertainment" } 
}, 
{ 
    title: "Post #3", 
    tags: { "entertainment", "music", "theatre" } 
}, 
{ 
    title: "Post #4", 
    tags: { "entertainment", "music", "concerts" } 
} 

所需的結果

如果我想要得到的與「娛樂」的標籤列表,它查詢職位,以找到類似的標籤。類似的標籤是當帖子被標記爲「娛樂」時也使用的標籤。

我希望能夠得到以下結果:

Tag  Count 
======== ====== 
music  2 (because there are 2 posts tagged with music + entertainment) 
concert 1 
theatre 1 
news  1 

有沒有辦法把它作爲接近越好?我能夠得到的最接近的是使用db.posts.find({tags: "entertainment"});,然後在MongoDb之外循環並構建這些值。我正在尋找更有效的方法。

回答

1

您可以將工作推到寫入側以保持快速讀取。假設您正在嘗試將new_tag添加到已有some_list_of_tags的帖子中。下面的代碼將建立一個收集所需值:

for old_tag in some_list_of_tags: 
    db.related_tags.update({'_id':new_tag}, {'$inc':{'counts.'+old_tag:1}}, upsert=True) 
    db.related_tags.update({'_id':old_tag}, {'$inc':{'counts.'+new_tag:1}}, upsert=True) 

然後得到「娛樂的結果,只是做:

db.related_tags.find({'_id': 'entertainment'}) 

可以使用findAndModify命令原子添加標籤一個帖子並獲取所有現有標籤:

old_tags = db.posts.findAndModify({query: {_id: ID}, 
            update: {$addToSet: {tags: new_tag}}, 
            fields: {tags: 1} 
            })['tags'] 
+0

我沒有想到該選項。好主意。 – Trevor 2011-01-07 19:52:12

0

你不會找到一個。 MongoDB具有非常有限的(但非常有效的)查詢功能。對於像你這樣的東西需要map/reduce,但是因爲今天的MongoDB M/R是單線程的,而且它的JS引擎並不是最快速的,所以你最終可能已經擁有了最好的解決方案。