According to nodejs documentation the following is deprecated:
This is not how you
If you do not use a projection a document fetch will occur. So yes it is better to projection. I am not too sure what happens internally when you specify an empty projection. You might have a document fetch even if it is not needed. I think it would be better to project _id to make sure the query hits the logic of a covered query.
I have no numbers to confirm my gut feeling expressed above.
@steevej _id is added to projection automatically. Only why I asked is, that I wont to be sure, that I’m using right way for that (especially in that case, when there is a lot of documents in collection or document size is bigger and projection /I think/ can be more effective like selection whole document).
Thanks a lot for your answer Nobody else answered.
Make sure there the fields you are repeatedly looking for is indexed properly
Searching for one exact match will be faster than going over many. I would do the first option.
I would test each option for speed and the execution summary to verify which one is most efficient.
Below I ran a simple test (in python) and got the round trip execution time. Most of the time is network travel.
#read Object ID Document from the collection
from bson.objectid import ObjectId
HOST = vmhost
print(bcolors.OKBLUE + "[+] Reading the data of the collection"+ bcolors.ENDC)
t0 = time.time()
with MongoClient(HOST) as client:
db = client['collection']
#db.test_col.insert_one({"foo": "bar"})
with db.test_col.find_one({'_id': ObjectId('6446d2d85d69b01f140dd453')}) as cursor:
for c in cursor:
print(c)
t1 = time.time()
total = t1-t0
print("Execution Time: {}".format(total))
Results
[+] Reading the data of the collection
{'_id': ObjectId('6446d2d85d69b01f140dd453'), 'foo': 'bar'}
Execution Time: 0.2895638942718506