Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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.

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.

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.

Is there any way i could accomplish that in mongo. I am using nodejs with mongojs. 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);
            }
          });   
Problem courtesy of: user3062634

Solution

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} 
                      ])
Solution courtesy of: Makis Tsantekidis

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×