1

I'm using MongoDB v5.

Most of my collections have temporal data, so each document has at least one datetime. Naturally I'm generally most interested in the most recent data, but by default mongo appears to return documents in insertion order.

How can I change this so the most recent data is shown first by default?

I'm currently either adding a sort manually, or creating a view manually for each collection with the sort defined.

I'm using MongoDB Compass if that makes any difference; I'm willing to consider a different tool if necessary.

1
  • Having an index on the field being sorted can help in terms of performance, especially for larger datasets. In general, the mongosh is the command line tool often preferred by developers and database administrators (this doesn't make difference in this specific use case).
    – prasad_
    Feb 23 at 5:31

1 Answer 1

1

by default mongo appears to return documents in insertion order.

MongoDB returns documents in natural order when no sort order is specified. Natural order is an undefined "as results are found" which may appear to coincide with insertion order, but is definitely not guaranteed or predictable.

I'm currently either adding a sort manually, or creating a view manually for each collection with the sort defined.

Either of these approaches would work, although setting up a view for every collection sounds like more effort. I assume that you are creating Indexes to Sort Query Results to support efficient queries.

I'm not aware of a tool that saves a default sort order per collection, but you could submit this as a feature suggestion for your favourite tools (for example: Compass feedback). A Compass feature suggestion like saving and restoring tabs with queries & sort settings may also address your use case and be worth upvoting and watching.

If you are extra motivated, you could always write a plugin for the MongoDB Shell or Compass. The scope of that would be more involved than a DBA Stack Exchange question and would be better discussed in the Developer Tools category on the MongoDB Developer Community Forums.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.