Best practice: Specifying required fields in mongodb queries?


Is there a difference between the following two queries with regard to performance (speed, memory, bandwith) on server or client? In other words, is it best to always specifiy the fields that you require or is the performance gain so minimal that I can avoid the effort?

var id = MyCollection.findOne()._id;

var id = MyCollection.findOne({}, fields: { "_id": 1 })._id;


Depends on what else is in MyCollection. Do you have 15megs of data in the document? Use the second line. I think for most applications, it’s negligible.

On the client, it doesn’t make a difference because it’s already in client memory and all you’re doing is providing a reference to it.

EDIT: Actually, I normally do this:

var obj = MyCollection.findOne();

and leave it at that. Start optimizing when you start to see problems.