1

MongoDB scripting is still pretty cryptic to me, and stuck with this problem on a 3.6 server lacking the fancier operators from 4.2.

How to increase a date field with one second value in a MongoDB 3.6?

For example, I'd like to do something like this:

db.getCollection("therecords").update(
   { 
      "_id" : ObjectId("123etc")
   }, 
   { 
      $set: {
         updatedAt : "$updatedAt" + 1 ;
      }
   }
);

…will set the value to the text $updatedAt1 which is cute.

Other cute errors are thrown when using updatedAt without quotes or without the $ prefix.

More generically, is there a way to reuse current values with update … $set?

4

1 回答 1

1

I don't think it is possible to do this using single query in MongoDB v3.6, but:

  1. find() specific documents
  2. forEach() found document, get the date and bump
  3. save() it back
db.getCollection("therecords").find(
    { 
        "_id" : ObjectId("123etc") 
    }
).forEach(function(doc) {
   var d = new Date(doc.createdAt);
   d.setSeconds(d.getSeconds() + 1);
   doc.createdAt = d;
   db.getCollection("therecords").save(doc); // Save each back
});
于 2021-01-05T06:21:50.193 回答