Explain() error for findOne query

I try to find out whether my query using index properly to find one record (the earliest one).
However, looks like explain() is not supported for findOne() query?

How can I check the performance of findOne query using an index then?

For example, I created an index on record’s embedded array’s first item’s date to find out which record has the earliest date with the embedded array in asc time order already. And I want to make sure index scan is used when I do the query.

  1. The index on embedded array’s first item’s date
    db.getCollection(collection).createIndex({“RAUs.0.date”: 1}, {name: “rau_date_inc”})

  2. find one query to get the record with earliest date
    first_record = collection.find_one({‘RAUs.0.date’: {‘$exists’: True}}, sort=[(“RAUs.0.date”, 1)])
    if first_record:
    start_time = first_record[“RAUs”][0][‘date’]

I want to make sure the index works as expected.

Thank you!

Mary

The following works showing the index scan is used. However, I want to make sure above find_one query use the index scan too.

find({‘RAUs.0.date’: {‘$exists’: true, “$gt”: “2023-06-01T19:56:21.099Z”}}).explain()

Will find() with limit of 1 has same execution plan?

Hello,

It is a coding shortcut only.
findOne() is basically a shorthand to do a find().limit(1)

The query optimisation and execution are the same.

As you know while find returns a cursor, findOne returns a document instead. The method explain() belongs to cursor object. This is the reason it is not possible call explain with findOne.

Please read this discussion:

Thanks
WeDoTheBest4You

Furthermore:

Please see the implementation of findOne for Node driver.
The limit(-1) does the same as limit(1) still it closes the cursor.

This has also been included in the same post enclosed earlier.

 findOne(
...
    return this.find(finalFilter, finalOptions).limit(-1).batchSize(1).next(callback);
  }

Thanks
WeDoTheBest4You