简体   繁体   中英

mongodb: why indexOnly=false when collection is empty

Let's say I have an empty db without any collections. Then I run db.qqq.ensureIndex({a:1}) .

In the output of db.qqq.find().explain() I see BasicCursor and "indexOnly" : false . That seems OK.

db.qqq.find({a:"somevalue"}).explain() outputs BtreeCursor a_1 , but it also tells "indexOnly" : false . Why does this happen?

Why the given index isn't enough for mongodb to fulfill my query?

UPD : OK, so I need to use projection, since there is no all fields in my index. But what I don't understand -- if Mongo can see from index that there is no any documents matching query, then why should it scan the actual documents?

You need to add projection to that query, index only means it gets ALL data from the index. MongoDB cannot use an index only cursor if you want to get the full document back. So ie:

db.qqq.find({a:"somevalue"},{a:1,_id:0}).explain()

Should work.

MongoDB doesn't know that there are no documents until it searches for them, so it will have to at least check in the index if it can. A "BasicCursor" with "n=0" is not really a bad thing of course as no actual documents are read (or index elements, as there are none).

Also, if you want to use a covered index, you need to use a projection so that only fields are returned that are actually part of the index. You do that with:

db.qqq.find({a:"somevalue"},{a:1,_id:0}).explain()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM