-
Type: Improvement
-
Resolution: Duplicate
-
Priority: Minor - P4
-
None
-
Affects Version/s: None
-
Component/s: None
-
None
Hello! My name is Vladimir Revenko. I am NodeJS developer and active MongoDB user!
Problem
Tools such as Mongoose use the "timestamp" functionality. This makes it difficult in some cases.
If we run without a `timestamps` parameter mongoose does this:
{{db.cats.updateMany({}, { '$set':
{ name: 'Zildjian' }})}}
MongoDB returns this:
`matchedCount` — (`n` in Mongoose) containing the number of matched documents;
`modifiedCount` — (`nModified` in Mongoose) containing the number of modified documents.
But, if we run with `timestamps` mongoose (with pre-hook) does this:
db.cats.updateMany({}, {
'$setOnInsert': {
createdAt: new Date("Sat, 26 Sep 2020 17:56:54 GMT"),
},
'$set': {
updatedAt: new Date("Sat, 26 Sep 2020 17:56:54 GMT"),
name: 'Zildjian',
},
})
even if a `name` field is not modified, `updatedAt` field has been modified and MongoDB will update all matched docs and `modifiedCount` (`nModified` in Mongoose) will always be equal to `matchedCount` (`n` in Mongoose).
I think there are other examples, but timestamps are the most obvious example.
Suggestion for improvement
Maybe you should separate the targeting update fields and the companion update fields at the mongodb level?
Current usage works like this:
db.cats.updateMany({}, {
'$setOnInsert': {
createdAt: new Date("Sat, 26 Sep 2020 17:56:54 GMT"),
},
'$set': {
updatedAt: new Date("Sat, 26 Sep 2020 17:56:54 GMT"),
name: 'Zildjian',
},
})
New usage could be like this:
db.cats.updateMany({}, {
'$setOnInsert': {
createdAt: new Date("Sat, 26 Sep 2020 17:56:54 GMT"),
},
'$setOnUpdate': {
updatedAt: new Date("Sat, 26 Sep 2020 17:56:54 GMT"),
},
'$set': {
name: 'Zildjian',
},
})
Thе `$setOnUpdate` field means what data needs to be updated along with the data updated by the `$set` field.
- `matchedCount` = number of matched docs
- `modifiedCount` = number of modified only by the `$set` field
I think this will add flexibility when working with the database and, at the same time, it will not break the existing code.
Please see discussions with some examples:
- `nModified: 1` returned by `.update()` when $addToSet makes no modification
- [updateMany().nModified does not work correctly with timestamps
https://github.com/Automattic/mongoose/issues/9452] - updateMany() returns wrong nModified value
With best regards,
Vladimir Revenko
Email: vova@revenko.org
Telegram: @vovarevenko
- duplicates
-
SERVER-42084 Easy syntax for $setIfModified behavior
- Backlog
- related to
-
SERVER-13578 add $setOnUpdate to update operation
- Closed