Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda