Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
Mongodb giving different count results from count function and aggregation pipeline

I have a collection in mongodb named users. I am trying to find count of all documents in the collection.

Surprisingly following queries are giving different results. For

db.users.find({}).count()

and

`db.users.count()`

the output is 533911, and for

db.users.aggregate(
    [
        { $group: { _id: "$_id" } },
        { $group: { _id : null, count : { $sum : 1 } } }
    ]
)

and

db.users.aggregate(
        [
            { $group: { _id : null, count : { $sum : 1 } } }
        ]
    )

the output is 533950.

Can anyone tell me why aggregation and normal queries are returning different results ? Thanks in advance for any help.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I see 2 possible reasons :

  1. If your collection is sharded, you should use the aggregation framework to count documents because the count operation may be inaccurate due to chunk moves or orphaned documents. How to count in Sharded Clusters

  2. If you are using WiredTiger storage engine (which is most likely now as it's the default since V3.2), the statistics stored by WiredTiger can be inaccurate after an unclean shutdown. You should run a db.collection.validate() on each collections. WiredTiger unclean shutdown

Note : You can reduce the "confusion" by removing the orphaned documents with the cleanupOrphaned command but in a sharded environment you should always use the aggregation framework.

over 4 years ago · Santiago Trujillo Report

0

db.users.aggregate(
    [
        { $group: { _id: "$_id" } },
        { $group: { _id : null, count : { $sum : 1 } } }
    ]
) 

is counting null values also.

db.users.count()

not counting null values.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!