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

142
Views
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 answers
Answer question

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 Report

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 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!