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?
Asked
Active
Viewed 1.9k times
1 Answers
22
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 };
});
});

Alex Mamo
- 130,605
- 17
- 163
- 193
-
1can you please explain it.? – Dev Jan 14 '19 at 09:50
-
Give it a try and keep me posted. – Alex Mamo Jan 14 '19 at 09:54
-
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 ? – BluE_MoOn Jan 21 '20 at 22:26
-
1@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](https://stackoverflow.com/questions/50305328/firestore-whereequalto-orderby-and-limit1-not-working). – Alex Mamo Jan 22 '20 at 10:11
-
Is the `Date` property a field in the collection? Can it exist within a map? – Gabriel Apr 13 '20 at 09:23
-
@Max The `Date` property cannot exist in a collection, only in a document. And yes, the `Date can be added to a Map. – Alex Mamo Apr 13 '20 at 09:38
-
An example would be very useful! – Daniel Jun 24 '20 at 12:37
-
Thank you @AlexMamo! – Daniel Jun 24 '20 at 13:17
-
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 – 1x2x3x4x Jun 09 '21 at 09:25
-
1@1x2x3x4x Yes, it will be indeed **only** one read, as your query only one document returns. – Alex Mamo Jun 09 '21 at 09:56