Documents Count करना
countDocuments matches को accurately count करता है और estimatedDocumentCount एक fast total देता है।
In this page:
Syntax
db.collection_name.countDocuments(filter)
db.collection_name.estimatedDocumentCount()
Documents Count करना
countDocuments(filter) query चलाता है और एक exact count return करता है, जब हो सके indexes इस्तेमाल करते हुए। estimatedDocumentCount() एक बहुत fast approximate total के लिए collection metadata पढ़ता है और कोई filter नहीं लेता। distinct(field) unique values का set return करता है।
Note:
huge collections पर dashboards के लिए estimatedDocumentCount इस्तेमाल करें।
उदाहरण: Counting documents
test> db.users.insertMany([
... { _id: 1, city: "Oslo", active: true }, { _id: 2, city: "Oslo", active: false },
... { _id: 3, city: "Rome", active: true }, { _id: 4, city: "Lima", active: true }
... ])
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.users.countDocuments()
4
test> db.users.countDocuments({ active: true })
3
test> db.users.estimatedDocumentCount()
4
test> db.users.distinct("city")
[ 'Oslo', 'Rome', 'Lima' ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- deprecated count इस्तेमाल करना
- यह उम्मीद करना कि estimatedDocumentCount एक filter accept करेगा
- सारे documents fetch करके count करना
चैप्टर सारांश
- countDocuments(filter) exact है
- estimatedDocumentCount fast और unfiltered है
- distinct unique values list करता है
- सब कुछ fetch करके count न करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: