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

139
Vistas
Find empty documents in a database

I have queried an API which is quiet inconsistent and therefore does not return objects for all numerical indexes (but most of them). To further go on with .count() on the numerical index I've been inserting empty documents with db.collection.insert({})

My question now is: how would I find and count these objects? Something like db.collection.count({}) won't work obviously.

Thanks for any idea!

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Use the $where operator. The Javascript expression returns only documents containing a single key. (that single key being the documents "_id" key)

db.collection.find({ "$where": "return Object.keys(this).length == 1" }).count()
over 4 years ago · Santiago Trujillo Denunciar

0

For MongoDB 3.4.4 and newer, consider running the following aggregate pipeline which uses $objectToArray (which is available from MongoDB 3.4.4 and newer versions) to get the count of those empty documents/null fields:

db.collection.aggregate([
    { "$project": {
        "hashmaps": { "$objectToArray": "$$ROOT" } 
    } }, 
    { "$project": {
        "keys": "$hashmaps.k"
    } },
    { "$group": {
        "_id": null,
        "count": { "$sum": {
            "$cond": [
                {
                    "$eq":[
                        {
                            "$ifNull": [
                                { "$arrayElemAt": ["$keys", 1] },
                                0
                            ]
                        },
                        0
                    ]
                },
                1,
                0
            ]
        } }
    } }
]); 
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