MongoDB query to add timestamp only if it is not present

To add a timestamp field only if it is not already present in MongoDB documents, use the $exists operator with update() and set multi: true to update multiple documents at once.

Syntax

db.collection.update(
    { "fieldName": { $exists: false } },
    { $set: { "fieldName": new Date() } },
    { multi: true }
);

Sample Data

db.demo479.insertMany([
    { "DueDate": ISODate("2020-01-10"), "Name": "Chris" },
    { "Name": "David" },
    { "DueDate": ISODate("2019-12-31"), "Name": "Bob" },
    { "Name": "Carol" }
]);

Display all documents to see the initial state ?

db.demo479.find();
{ "_id" : ObjectId("5e820733b0f3fa88e2279094"), "DueDate" : ISODate("2020-01-10T00:00:00Z"), "Name" : "Chris" }
{ "_id" : ObjectId("5e820748b0f3fa88e2279095"), "Name" : "David" }
{ "_id" : ObjectId("5e82075fb0f3fa88e2279096"), "DueDate" : ISODate("2019-12-31T00:00:00Z"), "Name" : "Bob" }
{ "_id" : ObjectId("5e820767b0f3fa88e2279097"), "Name" : "Carol" }

Example: Add Timestamp Only Where Missing

Add DueDate field only to documents that don't already have it ?

db.demo479.update(
    { DueDate: { $exists: false } }, 
    { $set: { "DueDate": new Date() } }, 
    { multi: true }
);
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

Verify Result

db.demo479.find();
{ "_id" : ObjectId("5e820733b0f3fa88e2279094"), "DueDate" : ISODate("2020-01-10T00:00:00Z"), "Name" : "Chris" }
{ "_id" : ObjectId("5e820748b0f3fa88e2279095"), "Name" : "David", "DueDate" : ISODate("2020-03-30T14:52:29.656Z") }
{ "_id" : ObjectId("5e82075fb0f3fa88e2279096"), "DueDate" : ISODate("2019-12-31T00:00:00Z"), "Name" : "Bob" }
{ "_id" : ObjectId("5e820767b0f3fa88e2279097"), "Name" : "Carol", "DueDate" : ISODate("2020-03-30T14:52:29.656Z") }

Key Points

  • $exists: false matches documents where the field is missing
  • multi: true updates all matching documents in one operation
  • Documents with existing DueDate fields remain unchanged

Conclusion

Use $exists: false with multi: true to conditionally add timestamp fields only to documents that don't already have them, preserving existing values in other documents.

Updated on: 2026-03-15T03:07:03+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements