Question

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);
            }
          });   
Was it helpful?

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} 
                      ])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top