← Back to MongoDB Course | Chapter 3: CRUD — Read | Lesson 7 of 7

Documents Count करना

countDocuments matches को accurately count करता है और estimatedDocumentCount एक fast total देता है।
Syntax
javascript
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

bash
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. #}
आम गलतियां
  1. deprecated count इस्तेमाल करना
  2. यह उम्मीद करना कि estimatedDocumentCount एक filter accept करेगा
  3. सारे 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.