I have found a way to force MongoDB to use the index:
db.table_name.find({field_name: {$exists: true}}).hint("field_name_index_name")
I created index field_name_index_name as
db.table_name.ensureIndex({field_name: 1},{sparse: true})
When I run explain(), indeed it had used the index.
However, there is another problem. I have totally 269702 entries in the table, and 7 queries. There is index for each query.
Here are some of the numbers:
Query1: (obj scanned)8 (returned) 8, (old time, ms)1005, (new time, ms)0
Query2: (obj scanned)508134 (returned)268188 (old time, ms)1034, (new time, ms)1906
Query3: (obj scanned)1431084 (returned)269566 (old time, ms)978, (new time, ms)4695
Query4: (obj scanned)2 (returned)2 (old time, ms)984, (new time, ms)0
Query5: (obj scanned)189699 (returned)172957 (old time, ms)1032, (new time, ms)793
Query6: (obj scanned)36111 (returned)34848 (old time, ms)989, (new time, ms)198
Query7: (obj scanned)394 (returned)294 (old time, ms)984, (new time, ms)3
Queries 1, 4, 6, and 7, the performances have improved greatly. For Query 5, it was good, but for Queries 2 and 3, it was getting worse. I could not understand, there are only 269702 entries in the table, how can query 2 have 508134 scanned objects, and query 3 have 1431084 scanned objects. There are more scanned objects than the number of entries in the table.
Could someone help me with this problem, please! Thank you very much!