Find empty documents in a database

流过昼夜 提交于 2019-12-11 05:53:36

问题


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!


回答1:


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()



回答2:


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
            ]
        } }
    } }
]); 


来源:https://stackoverflow.com/questions/41926988/find-empty-documents-in-a-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!