Search code examples
node.jsmongodbmongoose

Mongoose findOne() vs limit(1)


Using MongoDB and the Mongoose driver for Node.js, I want to limit the amount of code I have to repeat in my API.

Instead of doing something like this:

var limit  = req.query.limit || -1;


if(limit === 1){

Model.findOne({})...

}
else{

Model.find({})...

}

it would be better just to do:

var limit  = req.query.limit || -1;
Model.find({}).limit(limit);

So I have two questions:

(1) Does using limit(1) have the same effect as findOne() where it is a much more efficient search because the query returns as soon as it find its first match?

(2) Does limit(-1) or limit(0) have the effect have creating no limit to the search? Because this will make it possible to not have repeat code.


Solution

  • limit(1) vs findOne()

    • find returns a cursor whereas findOne returns the exact document.
    • It is faster to use find() + limit() because findOne() will always read + return the document if it exists.
    • find() just returns a cursor (or not) and only reads the data if you iterate through the cursor.
    • find() has a cursor and hence you can use explain() with your query in the mongo shell to see the winning plan and other details on the execution of your query

    limit(-1), limit(0)

    • A limit() value of 0 (i.e. .limit(0)) is equivalent to setting no limit.
    • A negative limit is similar to a positive limit but closes the cursor after returning a single batch of results.

    http://docs.mongodb.org/manual/reference/method/cursor.limit/