Skip to content

Firestore limit_to_last(n) returns the first n elements in a reverse order instead of returning the last n elements #536

@brenhr

Description

@brenhr

Describe your environment

  • SDK version: 2.3.4
  • Python version: 3.10.2
  • Pip version: 21.2.4

Describe the problem

As per the documentation for limit_to_last clause, it should return the last n elements that match the query. However, when executing a simple query (i.e. db.collection("numbers").order_by("number").limit_to_last(5)) it returns the first 5 elements but in a reverse order.

Steps to reproduce

Create a collection and add data (in my case, I created a "numbers" collection, and inserted a total of 50 documents (from number 0 to 49) as follows:

for i in range(50):
    db.collection('numbers').document(f'{i}').set({
        'number': i
    })

And then, execute the following query and print the results:

lastDocs = db.collection('numbers').order_by("number").limit_to_last(5).get()
print('Last docs [using limit_to_last() clause]')

for doc in lastDocs:
    print(f'{doc.to_dict()}')
Expected output:
Last docs [using limit_to_last() clause]
{'number': 45}
{'number': 46}
{'number': 47}
{'number': 48}
{'number': 49}
Real output:

Screen Shot 2022-02-05 at 19 32 46

In case you find it useful, I also tried to reproduce this behavior in the Node.js Admin SDK, and I obtained the desired output (I mean, limitToLast() works perfectly fine):
Node.js code:

var numbersRef = db.collection("numbers");

console.log("Last documents [using limitToLast()]:");

numbersRef.orderBy("number").limitToLast(5).get().then((snapshot) => {
  snapshot.docs.forEach(doc => {
    console.log(doc.data());
  })
});

Node.js output:
Screen Shot 2022-02-05 at 19 31 26

Thanks.

Metadata

Metadata

Assignees

Labels

api: firestoreIssues related to the googleapis/python-firestore API.priority: p2Moderately-important priority. Fix may not be included in next release.type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions