python-3.xmongodbpymongopymongo-3.xflask-pymongo

How to find the max length of an array from a set of documents present in a collection in MongoDB?


I have 'n' number of documents present inside a collection in MongoDB. Structure of those documents is as follows:

{
    "_id": "...",
    "submissions": [{...}, ...]
}

I want to find the document which has the highest number of submissions out of all the documents present. Is there any Mongo find/aggregation query which can do the same?


Solution

  • I don't think any straight way to achieve this,

    You can try below aggregation query,

    collection.aggregate([
      { $addFields: { totalSubmissions: { $size: "$submissions" } } },
      { $sort: { totalSubmissions: -1 } },
      { $limit: 1 }
    ])
    

    Playground