How to store a sorted list in Google Firestore

How would you store an ordered list of N items in Google Firestore?

For example, a todo list. I had a couple of ideas but neither seem that smart.

You could put a 'position' key on the item but that would require updating all of the items' position value when one changes.

You could store them in a sorted array and do some splicing to resort before persisting.

I'd be keen to hear what is the recommend approach.


You could store two lists in Firestore. One with your actual data (unordered) and the other with a map of id to order.

Here's a Dart example:

main() {

  List myList = [
    {'id': 'red', 'test': 'some data'},
    {'id': 'green', 'other': 'some other data'},
    {'id': 'blue'},
  ];

  List myOrderList = ['green', 'red', 'blue'];

  List orderByOtherList(List theList, String commonField, List orderList) {
    List listOut = [];
    orderList.forEach((o) => listOut.add(theList.firstWhere((m) => m[commonField] == o)));
    return listOut;
  }

  print(myList);
  print(orderByOtherList(myList, 'id', myOrderList));
}

Here's the example on DartPad: https://dartpad.dartlang.org/dc77acd6e4cfce608796a51cda3ee9ad

Then combine the streams with combineLatest2 from rxdart to order the actual list in your app whenever either list changes.

This example uses Dart, but you should be able to create something similar in other languages.


Firestore doesn't "store sorted lists" as one of its features. What it will do is build an index of documents in a collection using the values of document fields that you define. You can then sort documents based on that index. What you do with those document fields is completely up to you. If you need to re-write the values to suit your intended ordering, then do that.