将日期Y-m-d转换为MongoDate

时间:2013-10-10 18:21:42

标签: mongodb

我需要一个查询来优化我的数据集合并将所有字段date_passport从Y-m-d格式转换为MongoDate格式,这可能只是使用mongo查询?

目前:

{
    _id: ObjectId("522e261a7ecb75b34e000000"),
    type: "Chat",
    last_name: "Test",
    date_passport: '2013-11-28'
}

需要:

{
    _id: ObjectId("522e261a7ecb75b34e000000"),
    type: "Chat",
    last_name: "Test",
    date_passport: ISODate("2013-11-28T02:00:00.%LZ")
}

1 个答案:

答案 0 :(得分:0)

我在这里解决这个问题:

如果您的数据是dd / mm / YYYY

db.customer.find(
    {
        date_passport : {$nin : ['', undefined]} // find for not is empty or undefined documents
    }
).forEach( function(obj) {
    if (typeof(obj.date_passport)!='object') { //check if is not already a ISODate
        var datePt = obj.date_passport.split('/'); //split the string dd/mm/YYYY
        var dateEn = datePt[2] + '-' + datePt[1] + '-' + datePt[0]; // reorganize to YYYY-mm-dd

        obj.date_passport = new ISODate(dateEn); // convert in ISODate
        db.customer.save(obj); //save and thats all
    }
});

如果您的数据已经是YYYY-mm-dd

db.customer.find(
    {
        date_passport : {$nin : ['', undefined]} // find for not is empty or undefined documents
    }
).forEach( function(obj) {
    if (typeof(obj.date_passport)!='object') { //check if is not already a ISODate
        obj.date_passport = new ISODate(obj.date_passport); // convert in ISODate
        db.customer.save(obj); //save and thats all
    }
});