Skip to content
Studio 3T - The professional GUI, IDE and client for MongoDB
  • Tools
    • Aggregation Editor
    • IntelliShell
    • Visual Query Builder
    • Export Wizard
    • Import Wizard
    • Query Code
    • SQL Query
    • Connect
    • Schema Explorer
    • Compare
    • SQL ⇔ MongoDB Migration
    • Data Masking
    • Task Scheduler
    • Reschema
    • More Tools and Features
  • Solutions
  • Resources
    • Knowledge Base
    • MongoDB Tutorials & Courses
    • Tool/Feature Documentation
    • Reports
    • Case Studies
    • Whitepapers
    • Blog
    • Testimonials
    • Community
  • Contact us
    • Contact
    • Sales Support
    • Feedback and Support
    • Career
    • About Us
  • Store
    • Buy Now
    • Preferred Resellers
    • Team Pricing
  • My License
  • Download
search

How and when should I add timestamps to my MongoDB documents #Studio3T_AMA

Posted on: 03/11/2021 by DJ Walker-Morgan

Q: How and when should I add timestamps to my MongoDB documents? And can I do it with Studio 3T?

Welcome to the latest Studio 3T Ask Manatees Anything – #Studio3T_AMA. Want to know how to use Studio 3T to make your MongoDB life better? Just tweet and use #Studio3T_AMA or email [email protected].

A: If you have documents that change over time, then timestamps are great for keeping track of changes in those documents. 

In a previous AMA we showed how you can get by using the timestamp embedded into a document’s server-generated _id when the document is created. That gives you a creation date, but it doesn’t address updating at all. Worse still, that creation date is both sticky and fragile. Sticky because if you move the document to another server, the _id timestamp will still point to the original creation date. Fragile because if you regenerate the _id, all the creation date information is replaced with the current time.

So while it is handy to know there is a timestamp in server generated _id fields, you should never build your application architecture around using them. Instead, you should look to adding two (or more) explicit fields for timestamps.

Writing timestamps

Making sure that all your applications create and update MongoDB timestamps is going to be the hardest part of this process; MongoDB has no automatic timestamp support, so every one of your applications is going to have to make sure they do one of two things when working with the database: write a createdAt field, or update an updatedAt field. 

An exception might be if you use a package like Mongoose to work with MongoDB. It has support for adding automatic timestamps to your application’s schema. If your application framework hasn’t got that, it is down to developer rigor to make sure timestamp fields are managed correctly.

In practice, that means when inserting a document for the first time, you set the “createdAt” field in your schema to the current date, e.g new Date(). You’ll typically want to set the updatedAt field to the same value. When modifying a document, you’ll just need to set the updatedAt field with the current Date.

Writing timestamps in Studio 3T

Let’s step through this practically with a very simple schema, a name field and timestamp fields createdAt and updatedAt. Let’s insert a document into that collection:

Inserting with a timestamp into MongoDB

We’re using ISODate() to generate a timestamp here, date and time at GMT+0. Don’t ever think about timestamps in any other timezone. You just need a dependable, regular and consistent timestamp and UTC aka GMT+0 is your only option.  If we add this document and then pull it up in the viewer, we’ll see:

Viewing some MongoDB timestamps

ISODate() with no parameters is the current date, ISODate with a string parameter gets that string parsed into a date value. Notice how the two date strings end with “+0000”. That means these are UTC dates.

Now, if we want to edit this record, we have to remember to preserve the createdAt and update the updatedAt. Like this:

Updating a MongoDB timestamp with Studio 3T

We’re changing our name field to "Document Three Three Three", but more importantly we are updating the updatedAt field with ISODate() and not changing the createdAt field. If we check the results:

Viewing updated MongoDB timestamps

With An Update

Most of the time, we update documents rather than completely replace them. So let’s look at how to refresh MongoDB timestamps in an update. We’ll select the "Document Three Three Three" value in our Table View and bring up the Update Dialog by clicking on the icon:

Using update to update MongoDB timestamps

Ok, this update will only affect this particular document. Learn more about Update in Smart and Safe MongoDB Multi-Documents Updates. Clicking on the Update tab will show the change we would make:

Setting up the update query

This is actually no change at all. Update has simply created a template based on the currently selected field. If we just changed the value of the name, updatedAt would not be changed, so we should need to update that too:

Setting up the update to also update the MongoDB timestamp

Again, we update it with ISODate() to write in the current date. Click Update and then view the document:

The update result with updated UpdatedAt

And there we can see the updatedAt is, indeed, updated.

Node.js/JavaScript timestamps

As a final example, here’s some Node.js/JavaScript code which does a similar update to the one above:

var result = await collection.updateMany(
           { _id: ObjectId("6169898bc8646c0c1127e257") },
           { $set: { name: "Three Again", updatedAt: new Date() } }
         );

Which just updates the updatedAt field. When you are creating new documents, you can use the same procedure:

var result = await collection.insertOne({
     name: "Four",
     createdAt: new Date(),
     updatedAt: new Date(),
   });

The Truth about MongoDB Timestamps

Now here’s something you need to know. We’ve been talking about timestamps in this article, these timestamps have nothing to do with the Timestamp type in MongoDB. Our timestamps are simply Date types and nothing more. Always keep your timestamp information in Date objects. The MongoDB Timestamp type is actually an internal MongoDB BSON type that you should not use. Using Date types in your collections is best practice. They are easily read and set and portable.

Now, all you need to do is add timestamps to your applications and remember when updating to update the updatedAt field, or whatever you decide to call it. 


How helpful was this article?
This article was hideous
This article was bad
This article was ok
This article was good
This article was great
Thank you for your feedback!

About The Author

DJ Walker-Morgan

Dj has been around since Commodore had Pets and Apples grew everywhere. With a background in Unix and development, he's been around the technology business writing code or writing content ever since.

Related articles

  • 5 Reasons You Should Install A Local MongoDB Database
  • Which Studio 3T Logs Should You Send?
  • I’ve been invited to use Studio 3T – What should I do next?
  • Regularly finding the past week’s new documents when I don’t have a timestamp? #Studio3T_AMA
  • How to Copy and Paste MongoDB Documents

Tags

academy aggregation AMA atlas community connections date tags export features hackolade import intellishell JSON knowledge base migration modelling mongodb mongoodb productivity query regex releases schema security SQL Studio 3T tasks tips updates webinar windows

Browse by MongoDB topic

  • Connecting to MongoDB
  • Database Administration & Security
  • Getting Started with MongoDB
  • Getting Started with Studio 3T
  • Import/Export
  • Job Automation & Scheduling
  • MongoDB Aggregation Framework
  • MongoDB/Studio 3T Workshops
  • Performance
  • Query & CRUD Operations
  • Schema
  • Studio 3T Licensing
  • Support and other resources
  • Working with MongoDB & SQL
  • Working with MongoDB Atlas

Studio 3T

MongoDB Enterprise Certified Technology PartnerSince 2014, 3T has been helping thousands of MongoDB developers and administrators with their everyday jobs by providing the finest MongoDB tools on the market. We guarantee the best compatibility with current and legacy releases of MongoDB, continue to deliver new features with every new software release, and provide high quality support.

Find us on FacebookFind us on TwitterFind us on YouTubeFind us on LinkedIn

Education

  • Free MongoDB Tutorials
  • Connect to MongoDB
  • Connect to MongoDB Atlas
  • Import Data to MongoDB
  • Export MongoDB Data
  • Build Aggregation Queries
  • Query MongoDB with SQL
  • Migrate from SQL to MongoDB

Resources

  • Feedback and Support
  • Sales Support
  • Knowledge Base
  • FAQ
  • Reports
  • Case Studies
  • White Papers
  • Testimonials
  • Discounts

Company

  • About Us
  • Blog
  • Careers
  • Legal
  • Press
  • Privacy Policy
  • EULA

© 2022 3T Software Labs GmbH. All rights reserved.

  • Privacy Policy
  • Cookie settings
  • Impressum
When you click "Accept", you are agreeing to cookies being on your device. They may improve site navigation, site usage analysis, or the relevance of messages. It is up to you which cookies are enabled. Read our Privacy Policy.
Manage cookies
Accept
✕

Privacy Preference Center

A cookie is a small file of letters and numbers that is downloaded on to your computer when you visit a website. Cookies are used by many websites and can do a number of things, eg remembering your preferences, recording what you have put in your shopping basket, and counting the number of people looking at a website. In the form below you can choose which cookies, except for essential cookies, to allow or disable.

Accept all cookies

Manage consent preferences

Essential cookies are strictly necessary to provide an online service such as our website or a service on our website which you have requested. The website or service will not work without them.

Performance cookies allow us to collect information such as number of visits and sources of traffic. This information is used in aggregate form to help us understand how our websites are being used, allowing us to improve both our website’s performance and your experience.

Functional cookies collect information about your preferences and choices and make using the website a lot easier and more relevant. Without these cookies, some of the site functionality may not work as intended.

Social media cookies are cookies used to share user behaviour information with a third-party social media platform. They may consequently effect how social media sites present you with information in the future.

Accept selected