Anuj Panchal
Anuj Panchal

Reputation: 415

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?

Upvotes: 1

Views: 176

Answers (1)

turivishal
turivishal

Reputation: 36114

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

You can try below aggregation query,

  • $addFields to add new field totalSubmissions to get total elements in submissions array
  • $sort by totalSubmissions in descending order
  • $limit to select single document
collection.aggregate([
  { $addFields: { totalSubmissions: { $size: "$submissions" } } },
  { $sort: { totalSubmissions: -1 } },
  { $limit: 1 }
])

Playground

Upvotes: 1

Related Questions