Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

252
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda