2

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?

Gabriel R.
  • 1,186
  • 1
  • 15
  • 29
  • i don't think it is possible to do in single query in mongodb 3.6, you have to do 2 queries, first find and second update/save. – turivishal Jan 04 '21 at 17:42
  • I'd be happy to do it with multiple queries, in an aggregation or with some MongoDB Shell magic. I'd just prefer to stay in the MongoDB environment (i.e. via Studio 3T) and not install another tool or environment. – Gabriel R. Jan 04 '21 at 21:25

1 Answers1

2

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
});
Gabriel R.
  • 1,186
  • 1
  • 15
  • 29
turivishal
  • 34,368
  • 7
  • 36
  • 59