Home > Mobile >  Retrieve newest 2 documents from a collection
Retrieve newest 2 documents from a collection

Time:08-09

I need to retrieve the first 2 documents from a collection in google cloud firestore. The way I have thought of doing it is that I have the timestamp of the latest document, then subtract the number of milliseconds between first and last then retrieve that range.

let firstStamp: number = [example timestamp in ms]

const query: any = await admin.firestore().collection('collection').where('timestamp', '<', firstStamp);
let documents: any;
query.where('timestamp', '>', firstStamp - 15000);
return query.get().then(result => {
    if (result.size === 0) {
        log(`No data. If this happens i've done something wrong with my query.`);               
        return;
    };

    documents = result.docs;
});   

I get no error message no log, but this is not working. Can anyone see whats wrong?

If there is a better way to do this, please let me know.

CodePudding user response:

If you have a timestamp field in each of the document corresponding to its creation you can very easily query the two most recent ones as follows, using the orderBy() and limit() methods:

import { collection, query, orderBy, limit, getDocs } from "firebase/firestore";

const q = query(collection(db, "collection"), orderBy("timestamp", "desc"), limit(2));

const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  console.log(doc.id, " => ", doc.data());
});
  • Related