2012-11-09 37 views
0

我有博客文章的集合,以「票」字段中蒙戈DB:迭代與equals文件值

> db.posts.find({}, {_id:0, votes: 1}) 
{ "votes" : 1 } 
{ "votes" : 2 } 
{ "votes" : 2 } 
{ "votes" : 3 } 
{ "votes" : 3 } 

比我有一個Web界面來顯示每個頁面和控件(下一個職位,滬指)通過投票順序滑動帖子。我向當前投票計數的服務器發送next/prev帖子的請求,並選擇新的。所以我得到下一個查詢(每個http請求一個)

> db.things.find({vote: {$gt: 0}}, {_id:0, votes:1}).limit(1) // current votes == 0 
{ "votes" : 1 } 
> db.things.find({vote: {$gt: 1}}, {_id:0, votes:1}).limit(1) // current votes == 1 
{ "votes" : 2 } 
> db.things.find({vote: {$gt: 2}}, {_id:0, votes:1}).limit(1) // current votes == 2 
{ "votes" : 3 } 
... 

正如你可以看到跳過等於「票」的文件。所以我需要一些方法來使文檔具有唯一性並迭代等於投票(投票字段可能會經常更新並且每個文檔都有許多相等的值)。

有什麼辦法可以解決這個問題嗎?看起來我需要某種搜索索引。但正如我所說的標準領域的變化非常頻繁,我計劃有一個數百萬的文件。這意味着索引更新將是非常昂貴的操作,我希望更新系統的安全響應。

回答

0

如果你不在乎什麼樣的順序,結果回來的,你應該_id對它們進行排序,然後使用{$gt: current_id}獲得下一個:

db.things.findOne({}, {votes: 1}).sort({_id: 1}) // _id == 0 
db.things.findOne({_id: {$gt: 0}}, {votes: 1}).sort({_id: 1}) // _id == 1 
db.things.findOne({_id: {$gt: 1}}, {votes: 1}).sort({_id: 1}) // _id == 2 
... 

如果你需要他們通過votes排序,然後你需要使用skip代替:

db.things.findOne({}, {votes: 1}).sort({votes: 1}) 
db.things.findOne({}, {votes: 1}).sort({votes: 1}).skip(1) 
db.things.findOne({}, {votes: 1}).sort({votes: 1}).skip(2) 
... 

但是你一定要越走越跳躍到結果集變得越來越慢。