在MongoDB中将字符串日期更改为ISO日期? [英] Change String date to ISO date in MongoDB?

查看:245
本文介绍了在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);
})

这篇关于在MongoDB中将字符串日期更改为ISO日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆