在MongoDB上,当我的回调在“find”中时,如何限制查询?

时间:2012-04-02 03:07:34

标签: node.js mongodb

我在MongoDB中有这个查询

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

它完美无缺,除了我得到50个结果。

我试过这个:

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

但这也没有帮助,所以我在下面尝试了这个也没有帮助限制它。

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

如何限制此查询的结果数量,仍然以与我相同的方式调用回调?

1 个答案:

答案 0 :(得分:22)

你几乎是对的。试试这个:

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

语法为find(query, fields, options)。我们需要那个空对象来正确地创建驱动程序解释选项。