Updatemany updates the updatedAt timestamp (using Mongoose) of all the records. Does it make it slow as it needs to go through all records

Hello ,
I am using updateMany to update a field on the matching records .
I was surprised to learn that all(matching as well as not matching the condition ) the documents had their updatedAt time stamp updated. Questions :
a) is there a way not to update the timestamps where there is no match
b) does it make it a slower operation as all the documents are updated as opposed to a doing single update operation in a loop (especially when i know only a few documents need to updated out of Thousands/Millions )

Thanks in advance!

Hi @Anurag_Negi ,

Can you share the update statement and its filter ?

Also a document sample?

Ty
Pavel

Hi @Pavel_Duchovny ,

Below are the details :

  • backend is implement in/via Node/express

  • Mongoose library for interfacing with Mongo db

  • update statement : (collection is named Notifications and an array of _ids are passed in req.body )

const updateResult = await Notifications.updateMany(
    { _id: { $in: req.body } },
    { $set: { isRead: true } }
  );
  • sample dcoument:
    _id:ObjectId(‘635e41c65abbd1082e2b40d7’)
    userId:ObjectId(‘62f26698d08902fa6ffab823’)
    fromUserId:ObjectId(‘6332fe3a9d679ece1d94c9f5’)
    isRead:true
    isClicked:false
    type:“like”
    itemType:“comment”
    createdAt:2022-10-30T09:20:06.131+00:00
    updatedAt:2022-10-30T09:37:34.015+00:00
    __v:0

  • Prob description : I am setting the isRead field to true for the _ids that are passed . This works fine and only those documents which match the ids passed gets the isRead field updated to true. However, updatedAt time stamp gets updated for “all” the documents in the collection and not just the matching records/documents.

  • Questions:
    a) is it less efficient compared to multiple find and update when the updates are only few records out of thousands/millions ?
    b) is there a way to update only the timestamp of the affected records and not all the records?

Many Thanks!

Hi @Anurag_Negi ,

Yes if you update all records with no filter the only way is to perform a full collection scan. This could be a resource intensive.

If you need to update only those ids record just add additional set:

const updateResult = await Notifications.updateMany(
    { _id: { $in: req.body } },
    { $set: { isRead: true , updatedAt : new Date()}}
  );

Thanks
Pavel

@Pavel_Duchovny Thanks for clarifying.