2

When running the code below I get the first item not the last. Why is that?

async def example():
    db: google.cloud.firestore.AsyncClient = AsyncClient()
    await db.document("1/1").set({"a": "1"})
    await db.document("1/2").set({"a": "2"})
    last = (
        await (
            db.collection("1")
            .order_by("a")
            .limit_to_last(1) # <= not working - getting the first not last
            .get()
        )
    )[0].to_dict()
    first = (
        await (
            db.collection("1")
            .order_by("a")
            .limit(1)
            .get()
        )
    )[0].to_dict()
    print(first, last) # {'a': '1'} {'a': '1'}


asyncio.run(example())

The workaround is the use of descending ordering with limit(). But I don't understand - what is the purpose of the limit_to_last() function?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Andrey
  • 5,932
  • 3
  • 17
  • 35

1 Answers1

3

If your database schema looks like this:

db
|
--- 1 (collection)
    |
    --- 1 (document)
    |   |
    |   --- a: "1"
    |
    --- 2 (document)
        |
        --- a: "2"

Then the following query:

db.collection("1").order_by("a").limit_to_last(1)

Will indeed return:

{'a': '2'}

Because the last element in the results is the second document. I tested and it worked. However, when you want to store numbers, it's not recommended to store them as strings but as numbers. Why? Because when you order strings the order is lexicographically.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Thanks. My scheme is exactly the same. I created database with `db.document("1/1").set({"a": "1"})`. If I change to `db.collection("1").document("1").set({"a": "1"})` - everything works as expected. Why is this? – Andrey Aug 29 '23 at 16:43
  • I'm not sure why when you're using `.document("1/1")` doesn't work correctly, maybe perhaps of an escape character. However, it's best to differentiate from the beginning a collection from a document by calling `.collection("1").document("1")`. – Alex Mamo Aug 30 '23 at 07:34
  • Did my answer help? Can I help you with other information? – Alex Mamo Aug 30 '23 at 08:00
  • I think your answer is helpful, thanks – Andrey Aug 30 '23 at 16:42
  • You're very welcome, Andrey. – Alex Mamo Aug 30 '23 at 16:44