Search code examples
mongodbmongodb-querysql-like

MongoDB finding the document with more fields


Is it possible to obtain, from a collection, the document with the highest amount of fields?

Collection

In this case, the returned value should be the second document or just 18.


Solution

  • You can use aggregation pipeline with $objectToArray stage starting from 3.4.4 version to convert all top key & value pair into document arrays followed by $group to find the $max with $size on keys.

    db.collection.aggregate([{
        $project: {
            arrayofkeyvalue: {
                $objectToArray: "$$ROOT"
            }
        }
    }, {
        $group: {
            _id: null,
            max: {
                $max: {
                    $size: "$arrayofkeyvalue.k"
                }
            }
        }
    }])