Reputation: 11
I need to query a mongoDB (version 4.0)collection with 100M documents based on indexed field.
For example if I have a collection of users and each user has a field of city which is a string and this field is indexed I want to ask how many users have some exact value in the city field (db.users.count({address:"New York"})
).
I see that the response time to is changing according to the number of results if there are 20M it is around 5 sec.
In the explain() I see that it using COUNT and there is index name
"stage" : "COUNT_SCAN"
and
"indexName" : "address_1"
My question is doesn't mongodb save the number of documents related to each indexed field key for quick retrieval without scanning? Is there a quick way to retrieve this information?
Upvotes: 0
Views: 232
Reputation: 2974
No it doesnt. However, another improvement possible:
db.users.ensureIndex({address:1});
db.users.find({{address: 'New York}).count();
Upvotes: 0
Reputation: 2675
You can do:
db.users.find({address: 'New York'}).count()
which I think it's faster since you have indexed address
key. I don't think that in mongoDB saves anywhere this information regarding how many items are in a collection based on an indexed key. Just retrieving the data using the indexed key and perform a .count()
should be pretty quick.
Upvotes: 0