Home > Net >  Is using limit(1) improving query performances mongoDB?
Is using limit(1) improving query performances mongoDB?

Time:08-11

A simple question, let's have this query : user_result = db.users.find({"_id": "anyID"})

Is it more performant than user_result = db.users.find({"_id": "anyID"}).limit(1) if i know that this query should return only one result.

CodePudding user response:

If you compare the results if .explain() you will find that the winning plan in both cases is IDHACK. .limit(1) will not provide any perf gains.

db.users.find({"_id": "anyID"}).limit(1).explain()
db.users.find({"_id": "anyID"}).explain()

Similar question on MongoDB WinningPlan IDHACK

Also, you probably want to do a findOne() in this case.

db.users.findOne({"_id": "anyID"})

Keep in mind that the return value of findOne() differs from that of find(). FindOne returns the document, whereas Find returns a cursor.

  • Related