On MongoDB how can I limit the query, when my callback is inside "find"?


Question

I have this query in MongoDB

db.privateMessages.find( 
    { $or : [ 
       {fromId: userId, toId: socket.userId} , 
       {fromId: socket.userId, toId: userId} ] 
    }, 
    function(err, messages) { pushSvdMsgs(messages); });

It works perfectly, except for the fact that I get 50 results.

I have tried this:

db.privateMessages.find( { $or : [ {fromId: userId, toId: socket.userId} , {fromId: socket.userId, toId: userId} ] }, function(err, messages) { pushSvdMsgs(messages); }).limit(10);

But that didn't help either, so I tried this below which also didn't help limit it.

db.privateMessages.find( { $or : [ {fromId: userId, toId: socket.userId} , {fromId: socket.userId, toId: userId} ] }, { $limit : 2 }, function(err, messages) { pushSvdMsgs(messages); });

How can I limit the number of results from this query, and still call the callback the same way I have?

1
9
6/24/2015 2:49:19 PM

Accepted Answer

You got it almost right. Try this one:

db.privateMessages.find( { $or : [ {fromId: userId, toId: socket.userId} , 
                                   {fromId: socket.userId, toId: userId} ] },
                         {}, 
                         { limit : 2 }, 
                         function(err, messages) { pushSvdMsgs(messages); });

The syntax is find(query, fields, options). We need that empty object to make driver interpret options correctly.

22
4/2/2012 3:22:05 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon