Change String date to ISO date in MongoDB?

心不动则不痛 提交于 2019-12-11 06:39:32

问题


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"
    }
] 

after that I run this script:

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")
}

I tried this also:

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();
}
})

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

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.


回答1:


You can use dateutil module (sudo pip install python-dateutil)

Following is the sample code which convert the ISO string into datatime object and then insert it into mongo database.

import datetime
import pymongo
import dateutil.parser

def getDatetimeFromISO(s):
    d = dateutil.parser.parse(s)
    return d

conn = pymongo.MongoClient()
db = conn.sampleDB
collection = db.test
post = {
    "user" : "test1",
    "date" : getDatetimeFromISO("2016-02-10T21:56:33.000Z")
}

collection.insert_one(post)
conn.close()

In MongoDB

> db.test.find().pretty()
{
    "_id" : ObjectId("5885b47156addb199a07bf26"),
    "date" : ISODate("2016-02-10T21:56:33Z"),
    "user" : "test1"
}

You can update the string dates to ISO format in mongoDB in similar fashion.




回答2:


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);
})


来源:https://stackoverflow.com/questions/41800853/change-string-date-to-iso-date-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!