Get last created document in a Firebase Firestore collection
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 };
});
});
![pepe](https://i.stack.imgur.com/2Ej9s.jpg?s=256&g=1)
pepe
Updated on June 09, 2022Comments
-
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 over 5 yearscan you please explain it.?
-
Alex Mamo over 5 yearsGive it a try and keep me posted.
-
BluE_MoOn over 4 yearsThe 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 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 about 4 yearsIs the
Date
property a field in the collection? Can it exist within a map? -
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 about 4 yearsAn example would be very useful!
-
Daniel about 4 yearsThank you @AlexMamo!
-
1x2x3x4x about 3 yearsThanks 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 about 3 years@1x2x3x4x Yes, it will be indeed only one read, as your query only one document returns.