/firebase-tutorials

How to order Firestore documents by timestamp?

Learn how to order Firestore documents by timestamp—set up Firebase, add server timestamps, and query with orderBy to retrieve your latest entries.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to order Firestore documents by timestamp?

 

Step 1: Set up Firebase in Your Project

 

To use Firestore, you first need to set up Firebase in your project. Ensure you have Firebase initialized and Firestore set up in your application. This can vary whether you're using Firebase with a web app or a mobile app.

For a web app, you can set it up as follows:





const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_PROJECT_ID.appspot.com",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID"
};

// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

For a mobile app using Firebase, you should follow Firebase’s official documentation for setting up Android or iOS.

 

Step 2: Create Firestore Collection with Timestamp

 

To store a timestamp with each document in your Firestore database, you need to include a timestamp field when adding documents. Ensure you define the created_at field with firebase.firestore.FieldValue.serverTimestamp() to get the server time.


const addDocumentWithTimestamp = async () => {
  try {
    await db.collection("your_collection_name").add({
      title: "Document Title",
      created\_at: firebase.firestore.FieldValue.serverTimestamp()
    });
    console.log("Document successfully written!");
  } catch (error) {
    console.error("Error writing document: ", error);
  }
};

 

Step 3: Query Firestore Documents Ordered by Timestamp

 

To query documents from your Firestore collection and order them by a timestamp, you can use the orderBy function. Here's an example:


const queryDocumentsOrderedByTimestamp = async () => {
  try {
    const querySnapshot = await db.collection("your_collection_name")
                                  .orderBy("created\_at", "desc")
                                  .get();

    querySnapshot.forEach((doc) => {
      console.log(`${doc.id} => ${JSON.stringify(doc.data())}`);
    });
  } catch (error) {
    console.error("Error querying documents: ", error);
  }
};

By specifying orderBy("created_at", "desc"), your documents will be returned in descending order based on the timestamp, meaning the most recent documents will be listed first.

 

Step 4: Handle Timestamp Data Type

 

It's crucial to understand how timestamps are stored in Firestore. When you retrieve documents and print timestamp fields, you'll notice they are JavaScript Date objects. Here's how you can format a timestamp:


querySnapshot.forEach((doc) => {
  const data = doc.data();
  const createdAt = data.created\_at.toDate(); // Convert Firestore timestamp to JavaScript Date object
  console.log(`Document ${doc.id} was created at: ${createdAt}`);
});

 

Step 5: Testing and Debugging

 

To ensure your Firestore querying functions work correctly, you need to test your code. Here are a few debugging tips:

  • Ensure your Firestore rules allow read/write as per your app's requirements.
  • Log meaningful messages and errors to the console to understand any issues.
  • Verify your Firebase setup, such as API keys and configuration, is correctly implemented.

By following these steps, you can successfully order Firestore documents by timestamp in your Firebase application.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022