I woud like to check by _id, if item exists, what is the effective way?

How to effective check, if document by _id exists in database?

import BaseModel from "./BaseModel";
export abstract class UsersModel extends BaseModel {
 // Search single item and and reduce results to minimum by fields
  public static checkExists(userId: string) {
    return !!Meteor.users.findOne({ _id: userId }, { fields: {} });
  // Search single item
  public static checkExists(userId: string) {
    return !!Meteor.users.findOne({ _id: userId });
   // Search multiple items with count
   public static checkExists(userId: string) {
    return !!Meteor.users.find({ _id: userId }).count();

Or there is not difference between this methods?
Thanks a lot.

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 :slight_smile: Nobody else answered.

I would agree that the fastest way to do this is:

  1. Make sure there the fields you are repeatedly looking for is indexed properly
  2. Searching for one exact match will be faster than going over many. I would do the first option.
  3. 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:

t1 = time.time()
total = t1-t0
print("Execution Time: {}".format(total))


[+] Reading the data of the collection
{'_id': ObjectId('6446d2d85d69b01f140dd453'), 'foo': 'bar'}
Execution Time: 0.2895638942718506

Yes it does. But an empty projection might be an edge case equivalent to no projection. That is why

explicitly to make sure that an empty does not end up being a fetch.