1

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?

Anuj Panchal
  • 391
  • 3
  • 15

1 Answers1

1

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

turivishal
  • 34,368
  • 7
  • 36
  • 59