1

I was looking for the way how to get a maximum value from a MongoDB collection, and I've found most of people recommend to sort first, and then get the first one from the result.

In general, sorting takes O(NlogN) time, but if the field that I want to sort is already indexed, it should take much less time.

So my question is,

  1. As I wrote in the title, does sort() of MongoDB run in O(1) time?
  2. If not, does MongoDB provide a faster way to get the max value?
Sejin Jeon
  • 338
  • 2
  • 4
  • 17
  • Getting the max value from an indexed field (without any other criteria) would indeed be O(1). Since the index is already sorted, you can just get the first entry from it. https://stackoverflow.com/a/40163474/14955 – Thilo Apr 03 '19 at 11:52

1 Answers1

2

As I wrote in the title, does sort() of MongoDB run in O(1) time?

NO, and neither MongoDB Documentation mentions about it.

If not, does MongoDB provide a faster way to get the max value?

NO, though there is another way of using aggregation pipeline by using $max but it's not as performant as $sort + $limit. Quoting from documentation

$sort + $limit Memory Optimization:

When a $sort precedes a $limit and there are no intervening stages that modify the number of documents, the optimizer can coalesce the $limit into the $sort. This allows the $sort operation to only maintain the top n results as it progresses, where n is the specified limit, and ensures that MongoDB only needs to store n items in memory.

Community
  • 1
  • 1
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • Thanks to your detailed explanation with links to the documentation but I still have a question. If it's [sort()](https://docs.mongodb.com/manual/reference/operator/update/sort/), not `$sort` for aggregation operator, Isn't it can take advantage of an index? – Sejin Jeon Apr 03 '19 at 12:12