-1

Assuming that there is no index, is there a significant performance difference between sorting based on just one field vs multiple fields?

db.movies.aggregate([
  { $sort: { likes: -1 } }
  { $limit: 100 }
])

vs

db.movies.aggregate([
  { $sort: { likes: -1, 
             views: -1, 
             comments: -1, 
             bookmarked: -1 , 
             dislikes: 1
           } 
  },
  { $limit: 100 }
])

If I am building an APP, will the second query scale? Would there be a significant increase in time cost

David Makogon
  • 69,407
  • 21
  • 141
  • 189
  • 3
    More generally, "Make it correct, make it clear, make it concise, make it fast.. in that order." (Wes Dyer) If correctness requires things sorted by multiple fields, performance doesn't matter. If it's not a correctness issue, why do it in the first place? – Kevin Krumwiede May 11 '23 at 22:29
  • 1
    Since your question is about "whether it will scale" an you clarify how large is your dataset, how big is your computer hardware ( if it is a single machine on-prem ). If your data is sharded or it is in cloud the scenario becomes more complex – Sumit S May 12 '23 at 01:00

1 Answers1

2

In an oversimplified way, it depends on

a) How much memory do you have on your computer

b) How big is your dataset - will it hold in memory

If it does, then the performance difference will be so insignificant that you will not detect it practically.

If it does not, you have to read from disk and possibly use swap on your computer, and then the difference will be significant.

Sumit S
  • 516
  • 5
  • 17