在MongoDB中将字符串日期更改为ISO日期?

问题描述:

在MongoDB中,我有一个文档,其中有一个名为日期"的字段,并且位于数组中.

In MongoDB, I have a document with a field called "date" and that is in array.

  {
"_id" : ObjectId("587627a2125a730f78a20859"),
"data" : [
    {
        "Number" : "359983007479839",
        "date" : "2016-02-10T21:56:33.000Z"
    }
] 

之后,我运行此脚本:

db.dummy.find().forEach(function(doc){
doc.mongodbdate = ISODate(doc.mongodbdate);
db.dummy.save(doc);
})

它给了我下面的输出;

And its giving me below output;

{
"_id" : ObjectId("588724ba2746360c04a51e4b"),
"data" : [
    {
        "Number" : "359983007479839",
        "mongodbdate" : "2016-02-12T18:01:06.000Z"
    }
],
"mongodbdate" : ISODate("2017-01-24T15:26:24.537+05:30")
}

我也尝试过:

var bulk = db.dummy.initializeUnorderedBulkOp(),
count = 0;

db.dummy.find().forEach(function(doc) {
bulk.find({ "_id": doc._id }).updateOne({
    "$set": { "mongodbdate": ISODate(doc.mongodbdate) }
})
count++;
if (count % 1000 == 0) {
    // Execute per 1000 operations and re-init
    bulk.execute();
    bulk = db.dummy.initializeUnorderedBulkOp();
}
})

它抛出错误: "message":无效的ISO日期"

its throws Error: "message" : "invalid ISO date"

我想将该字符串日期转换为ISO日期.我已对某些代码进行了更改,但是它以ISO格式添加了新日期,但我想更新它,而无需插入新日期. 我也有一个关于stackoverflow的解决方案,但是那是在文档中添加新字段,我认为这是因为数组,我想更新现有的字段.

I want to convert that string date into ISO date.I have changed with some code but its adding new date with ISO format but I want to update which is already available no need to insert new one. One solution I got on stackoverflow also, but that is adding new field in my document i think it is because of array,I want to update my existing one.

您只需要修改代码即可遍历数组.

You just need to modify your code to loop over the array as well.

db.dummy.find().forEach(function (doc) {
  doc.data.forEach(function (currentValue, index) {
    doc.data[index].mongodbdate = ISODate(currentValue.mongodbdate);
  });
  db.dummy.save(doc);
})