Skip to content Skip to sidebar Skip to footer

Pymongo Aggregate: Filter By Count Of Fields Number (dynamic)

Let's say I have an aggregation pipeline that for now leads to a collection with documents built like this: {'name': 'Paul', 'football_position': 'Keeper', 'basketball_position':

Solution 1:

maybe mongoDB has now a better way to handle this

Yes, you can now utilise an aggregation operator $objectToArray (SERVER-23310) to turn keys into values. It should be able to count 'dynamic' number of fields. Combining this operator with $addFields could be quite useful.

Both operators are available in MongoDB v3.4.4+ Using your documents above as example:

db.sports.aggregate([
          { $addFields : 
             { "numFields" : 
               { $size:
                 { $objectToArray:"$$ROOT"}
               }
             }
          }, 
          { $match: 
            { numFields: 
              {$gt:2}
            }
          }
])

The aggregation pipeline above, will first add a field called numFields. The value would be the size of an array. The array would contain the number of fields in the document. The second stage would filter only for 2 fields and greater (two fields because there's still _id field plus name).

In PyMongo, the above aggregation pipeline would look like:

cursor = collection.aggregate([
                         {"$addFields":{"numFields":
                                         {"$size":{"$objectToArray":"$$ROOT"}}}}, 
                         {"$match":{"numFields":{"$gt":2}}}
         ])

Having said the above, if possible for your use case, I would suggest to reconsider your data models for easier access. i.e. Add a new field to keep track of number of sports when a new sport position is inserted/added.

Post a Comment for "Pymongo Aggregate: Filter By Count Of Fields Number (dynamic)"