mandaputtra
mandaputtra

Reputation: 1070

find document that had specific number fields mongodb

my documents

Is this possible in mongodb to select only document that had 49 fields? So i select document that had an _id: ObjectId("5a4ad9c298767555dde892a2") then had 49 fields in it?

Upvotes: 1

Views: 60

Answers (1)

mickl
mickl

Reputation: 49945

You can use $objectToArray to get all fields from $$ROOT object as an array of keys and values. Then you can use $size to get the length of that array:

db.collection.aggregate([
    {
        $addFields: { numberOfFields: { $size: { $objectToArray: "$$ROOT" } } }
    },
    {
        $match: { numberOfFields: 49 }
    }
])

Upvotes: 1

Related Questions