Get last created document in a Firebase Firestore collection

14,391

Is there any way to get the last created document in Firebase Firestore collection?

Yes, there is! The simplest way to achieve this is to add a date property to each object in your collection, then simply query it according to this new property descending and call limit(1) function. That's it!

As @eyyo mentioned in his comment, here is a concrete example. Assuming that your database schema looks like this:

Firestore-root
  |
  --- history (collection)
        |
        --- docId (document)
             |
             --- date: June 24, 2020 at 6:46:25 PM UTC+3
             |
             --- //Other properties

This is the required query:

this.historyRef = afs.collection<History>('history', ref => ref.orderBy('date', 'desc').limit(1));
this.history = this.historyRef.snapshotChanges().map(actions => {
    return actions.map(a => {
        const data = a.payload.doc.data() as Hisotory;
        const docId = a.payload.doc.id;
        return { docId, ...data };
    });
});
Share:
14,391
pepe
Author by

pepe

Updated on June 09, 2022

Comments

  • pepe
    pepe about 2 years

    Is there any way to get last created document in Firebase Firestore collection? My requirement is when user signed I have to add a document in a collection named 'history'; When the user signed out I want to update that document with a field called 'signout'; So if i get the lastly added document it is very easy to update. Is there any way to do this?

  • pepe
    pepe over 5 years
    can you please explain it.?
  • Alex Mamo
    Alex Mamo over 5 years
    Give it a try and keep me posted.
  • BluE_MoOn
    BluE_MoOn over 4 years
    The problem with this solution is that you manually have to create a Index for every document it in the Firebase console. Is there any other way to get the latest document inserted ?
  • Alex Mamo
    Alex Mamo over 4 years
    @BluE_MoOn Simply adding a Date property does not require an index. The index is automatically created for you. If you need to query and order, yes, there an index is required.
  • Gabriel
    Gabriel about 4 years
    Is the Date property a field in the collection? Can it exist within a map?
  • Alex Mamo
    Alex Mamo about 4 years
    @Max The Date property cannot exist in a collection, only in a document. And yes, the `Date can be added to a Map.
  • Daniel
    Daniel about 4 years
    An example would be very useful!
  • Daniel
    Daniel about 4 years
    Thank you @AlexMamo!
  • 1x2x3x4x
    1x2x3x4x about 3 years
    Thanks for this, I was looking for something similiar. One question though. Doing ref.orderBy('date', 'desc').limit(1) will be ONE READ or Fireabase will consider you've read the whole collection? @AlexMamo
  • Alex Mamo
    Alex Mamo about 3 years
    @1x2x3x4x Yes, it will be indeed only one read, as your query only one document returns.