2014-01-14 31 views
0

我有我的服務器的路由爲「q = word/s = 0/t = 5」其中q是查詢字符串,s是起始文檔並且t是限制。如何獲得連續順序的n組文檔Mongodb

因此,對於第一個請求,我將查詢基於q的文檔,並顯示結果從0到5檢索結果。

對於下一個請求,比如q = word/s = 6/t = 5,我將不得不從文檔編號6開始顯示文檔直到10.等等。

有沒有什麼辦法可以在mongo中實現這一點。我正在用mongojs使用nodejs。 任何幫助表示讚賞。

var words = req.params.q.split(" "); 
    var patterns = []; 
    // Create case insensitve patterns for each word 
    words.forEach(function(item){ 
     patterns.push(caseInsensitive(item)); 
    }); 

db.collection('mycollection', function(err, collection) { 
      collection.find({index : {$all: patterns }}).skip((s-1)*t).limit(t).toArray(function(err, items) { 
      if(err || !items) { 
       res.header("Access-Control-Allow-Origin", "*"); 
       console.log('nothing'); 
       res.send([]); 
      } else { 
       res.header("Access-Control-Allow-Origin", "*"); 
       console.log(items); 
       res.send(items); 
      } 
      }); 
+0

爲什麼你有* T在你跳轉部分可用於每個查詢的查詢?如果你刪除這個,你應該得到你正在尋找的結果。 –

回答

0

可以使用聚合框架來做到這一點,因爲在這個問題你這個例子也不會產生你所描述的結果。

這是給你的服務器

collection.aggregate([ 
         { $skip : s }, 
         { $match : { index : { $all : patterns } } }, 
         { $limit : t} 
         ]) 
+0

這爲我工作,謝謝! – user3062634

+0

請接受問題,如果它適合你。 –