Do I need to sort an array before adding to the database?

{
  countries: ["US", "CA"]
}

and

{
  countries: ["CA", "US"]
}

For the purpose of indexes, do I need to sort the array before putting into the database?

Absolutely not. But you could.

Hi @Big_Cat_Public_Safety_Act,

To be clear, sorting array values will not have any benefit for indexing.

The only top of mind use cases I can think of for sorting array values would be if you always want to display the values in a certain order or use something like $slice to maintain a capped array size. For example, Use $slice and $sort with $push to save the highest three scores in an array.

Regards,
Stennie

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.