Home > Net >  What is the default "orderBy" criteria in firestore for fields with same value?
What is the default "orderBy" criteria in firestore for fields with same value?

Time:05-31

Suppose there's a collection of documents that have a specific field containing an integer.

doc1={id:'dskjb12312',value:10}
doc2={id:'trhb12312',value:10}
doc3={id:'wqfewf12',value:20}
doc4={id:'dtyjnr312',value:30}

Now if I do a query like the below I would get the 3 documents with their scores in the descending order.

collection('Collection').orderBy('value','desc').limit(3).get()

The first two documents would be like below since they are in descending order.

doc4={id:'dtyjnr312',value:30}
doc3={id:'wqfewf12',value:20}

What is the default way Firestore decides on the 3rd document since there are two documents with the same value of 30? Is it random or is there any pre-defined logic behind it?

I know that I can use a second "orderBy" on a different field to get an advanced query but just wanted to know what is the default behavior with a single "orderBy" where there are fields with the same values.

CodePudding user response:

Outside of the order that you specify in the query, the documents will be returned in the order of their document ID. So if two documents have the same value, the one with the "lower" document ID will come first.

I'm not sure how explicitly this is documented, but it's a natural consequence of how the documents are represented in the index that each query uses to determine the results. In addition to whatever field you define the index on, it will always also contain the document ID (or in the case of a collection group index, the document path) to ensure that each entry in the index is unique.

  • Related