Coding⏱️ 2 min read📅 2026-06-03

How to Fix: MongoDB: update every document on one field

Update UNIX timestamp in MongoDB documents with current timestamp.

Quick Answer: $db.collection.updateMany({}, { $set: { lastLookedAt: new Date().getTime() / 1000 } })

To update every document on one field in MongoDB, you can use the MongoDB client's updateMany method. This method allows you to specify a filter and an update operator.

🔍 Why This Happens

  • The problem arises because MongoDB's update operators are designed for updating specific fields, not entire documents. However, the updateMany method provides a workaround by allowing you to specify a filter that targets all documents.

🛠️ Step-by-Step Verified Fixes

Method 1: UpdateMany

  1. Step 1: Connect to your MongoDB instance using the MongoDB client.
  2. Step 2: Use the updateMany method, specifying a filter that targets all documents and an update operator that sets the lastLookedAt field to the current timestamp.

Method 2: Update All Documents

  1. Step 1: Connect to your MongoDB instance using the MongoDB client.
  2. Step 2: Use the updateMany method with an empty filter and an update operator that sets the lastLookedAt field to the current timestamp. However, be aware that this approach updates all documents, including those that don't have the lastLookedAt field.

🎯 Final Words

When updating large numbers of documents, it's essential to test your update operations thoroughly to avoid data loss or corruption. Additionally, consider using the MongoDB 4.2+ updateMany method with the $set operator for more efficient updates.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions