2012-11-09 45 views
3

我想在MongoDB中搜索基於標籤的文章:如何在mongodb查詢結果中獲取標籤計數?

> use test; 
> db.articles.save({ name: "article1", tags: ['one', 'two', 'three'] }); 
> db.articles.save({ name: "article2", tags: ['two', 'three'] }); 
> db.articles.save({ name: "article3", tags: ['one', 'three'] }); 
> db.articles.save({ name: "article4", tags: ['one', 'two', 'four'] }); 
> db.articles.save({ name: "article5", tags: ['four', 'five'] }); 
> db.articles.ensureIndex({ tags: 1 }); 
> db.articles.find({ $or : [ { tags: 'four' }, { tags: 'five' } ] }) 

{ "_id" : ObjectId("509d7b555bff77729a26a232"), "name" : "article4", "tags" : [ "one", "two", "four" ] } 
{ "_id" : ObjectId("509d7b555bff77729a26a233"), "name" : "article5", "tags" : [ "four", "five" ] } 

正如你可以看到查詢查找「四」或「十二五」,但我想獲得的結果排序「最佳匹配「(匹配的兩個標籤比匹配的一個標籤更好)。

我該如何做到這一點?地圖縮小?

在此先感謝:

哈維

回答

1

我真的很抱歉讓你們失望,但並沒有什麼蒙戈現在可以做的。 唯一的選擇是在應用程序端實現排序。我知道這可能效率太低,但沒有其他選擇。

的唯一的事情我可以幫你的建議替代

$or : [ { tags: 'four' }, { tags: 'five' } ] 

tags:{$in:['four','five']} 

這不會幫助你的查詢(我的意思是命令的結果),但它如果會有很多不同的標籤,將會更容易在服務器上創建它。