2014-01-14 50 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

请接受问题,如果它适合你。 –