How to update date field in mongo console?

前端 未结 3 457
小蘑菇
小蘑菇 2021-02-02 07:00

For example I want to update all records to \'2012-01-01\' ( \"time\" : ISODate(\"2011-12-31T13:52:40Z\") ).

db.test.update( { time : \'2012-01-01\' }, false,          


        
相关标签:
3条回答
  • 2021-02-02 07:24

    You need to create a new ISODate object like this:

    db.test.insert({"Time" : new ISODate("2012-01-10") });
    

    This is true both for updates and for queries. Note that your query syntax is incorrect, it should be

    db.test.update({ criteria }, { newObj }, upsert, multi);
    

    For example, to update all objects, consider

    db.test.update( {}, { $set : { "time" : new ISODate("2012-01-11T03:34:54Z") } }, true, true);
    

    Also note that this is very different from

    db.test.update( {}, { "time" : new ISODate("2012-01-11T03:34:54Z") }, true, false);
    

    because the latter will replace the object, rather than add a new field to the existing document or updating the existing field. In this example, I changed the last parameter to false, because multi updates only work with $ operators.

    0 讨论(0)
  • 2021-02-02 07:41

    You can do this in the old-school way by creating ISO date

      db.test.update({_id : 1}, {
          $set : {
             "time" : new ISODate("your current date")
          }
      });
    

    But note that with new Mongo 2.6 you will be able to update date to a current date really easy with $currentDate.

    db.test.update( { _id: 1 }, {
      $currentDate: {
          time: true,
      },
    })
    
    0 讨论(0)
  • 2021-02-02 07:50

    If you need to convert an existing date field (imported from MySQL format 'yyyy-mm-dd' f.e.) to ISODate you can loop through the documents this way:

    /usr/bin/mongo yourdbname --eval "db.yourcollectionname.find().forEach(function(doc){doc.yourdatefield = new ISODate(doc.yourdatefield);db.yourcollectionname.save(doc)});"
    
    0 讨论(0)
提交回复
热议问题