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.
The index on embedded array’s first item’s date
db.getCollection(collection).createIndex({“RAUs.0.date”: 1}, {name: “rau_date_inc”})
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’]
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.