{"success":true,"name":"count-mongodb-documents-with-the-right-tool-for-the-job","description":"Displaying counts or totals from MongoDB collections","category":"ai-brimind","path":"ai-brimind/count-mongodb-documents-with-the-right-tool-for-the-job/SKILL.md","file":"SKILL.md","content":"---\nname: count-mongodb-documents-with-the-right-tool-for-the-job\ndescription: \"Displaying counts or totals from MongoDB collections\"\n---\n\n# Count MongoDB Documents With the Right Tool for the Job\n\n## When to use\nProject uses MongoDB, and code counts documents for dashboards, pagination totals, or stats.\n\n## Example request\ncountDocuments({}) on a huge collection for a dashboard → scans to count; estimatedDocumentCount() reads metadata instantly when no filter is needed. Exact filtered count on every page load → the count query can cost more than the page query; cache it or show 'many'. Counting inside an aggregation → $count stage, or $group with $sum, keeps it in the pipeline. Pagination showing 'page 3 of 40,000' → question whether users need exact totals; 'load more' removes the count entirely. Each maps to 'counting is a query with its own cost — choose exact, estimated, or none deliberately'.\n\n## Instructions\nAct as a developer who treats every count as a query with a price tag, not a free property. When code needs a count from MongoDB: (1) classify the need — exact filtered count (business rule, billing), rough total (dashboard vibe), or pagination decoration, (2) pick the matching tool: countDocuments(filter) for exact counts (it actually runs the query shape, so it needs the same indexes as a find would); estimatedDocumentCount() for whole-collection totals (metadata read, near-free, but unfiltered and approximate); $count or $group/$sum stages when counting inside an aggregation, (3) for expensive counts shown on every request, apply a named strategy instead of paying repeatedly: cache with a TTL, maintain a counter document updated with $inc (the computed pattern), or redesign the UI to 'load more' so no total is needed, (4) never loop-fetch documents just to count them in JS. If the product truly needs exactness ('must this number be precise?') is unknown, ask — it changes the cost by orders of magnitude. Only implement once the count's precision requirement and cost are matched, and explain why the chosen counting method scales with the collection.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1150\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}