简体   繁体   English

我如何按顺序获取n套文档Mongodb

[英]How do I get n set of documents in a sequential order Mongodb

I have my server with the route as "q=word/s=0/t=5" where q is the query string, s is the starting document and t is the limit. 我的服务器的路由为“ q = word / s = 0 / t = 5”,其中q是查询字符串,s是起始文档,t是限制。

So for the first request I would query the documents based on q and would show the results from 0 to 5 of the results retrieved. 因此,对于第一个请求,我将基于q查询文档,并显示检索到的结果中从0到5的结果。

For the next request, say q=word/s=6/t=5, i would have to show the document starting from document number 6 upto 10. and so on. 对于下一个请求,例如q = word / s = 6 / t = 5,我将必须显示从6号文档开始到10号的文档,依此类推。

Is there any way i could accomplish that in mongo. 有什么办法可以在mongo中完成。 I am using nodejs with mongojs. 我在mongojs中使用nodejs。 Any help is appreciated. 任何帮助表示赞赏。

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);
            }
          });   

You can use aggregation framework to do that since your example in the question won't yield the results you are describing. 您可以使用聚合框架来执行此操作,因为问题中的示例不会产生您所描述的结果。

Here is the query you can use for every query that is given to your server 这是您可以用于提供给服务器的每个查询的查询

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM