2016-02-29 91 views
2

我有我的birthDate字符串格式是這樣的「2010-03-22」。我想在MongoDB中的Date類型中進行轉換。轉換日期從字符串格式到日期格式在mongodb

應該寫什麼db.patient.update()函數? 我想計算每個人的年齡。

我使用了How do I convert a property in MongoDB from text to date type?上的解決方案,但所有日期都轉換爲「1970-01-01T00:00:00.000Z」。

+0

你會使用什麼客戶端? C#,Java的JavaScript? - >可以指向需要的端口代碼 – profesor79

回答

1

一種方法是通過在分隔符"-"給定分裂的字符串。使用parseInt()到分隔字符串轉換爲數字,而new Date()構造函數建立從這些零件一個Date:第一部分將是今年,第二部分的一個月,一天的最後一部分。由於Date使用從零開始的月份數字,您必須從月份數字中減去一個。

下面演示了這種方法:

var cursor = db.patient.find({"birthDate": {"$exists": true, "$type": 2 }}); 
while (cursor.hasNext()) { 
    var doc = cursor.next(); 
    var parts = doc.birthDate.split("-"); 
    var dt = new Date(
       parseInt(parts[0], 10), // year 
       parseInt(parts[1], 10) - 1, // month 
       parseInt(parts[2], 10) // day 
      ); 
    db.patient.update(
     {"_id": doc._id}, 
     {"$set": {"birthDate": dt}} 
    ) 
}; 

對於特別大的集合打交道時提高性能,採取使用Bulk API批量更新,因爲你會被髮送業務的優勢服務器批量說500,它可以提供更好的性能,因爲您不會向服務器發送每個請求,只需要每500次請求一次。

以下演示了這種方法,第一個示例使用MongoDB版本>= 2.6 and < 3.2中提供的Bulk API。它通過改變OrderDate字段日期字段更新集合中的所有 文件:

var bulk = db.patient.initializeUnorderedBulkOp(), 
    counter = 0; 

db.patient.find({"birthDate": {"$exists": true, "$type": 2 }}).forEach(function (doc) { 
    var parts = doc.birthDate.split("-"); 
    var dt = new Date(
       parseInt(parts[0], 10), // year 
       parseInt(parts[1], 10) - 1, // month 
       parseInt(parts[2], 10) // day 
      ); 
    bulk.find({ "_id": doc._id }).updateOne({ 
     "$set": { "birthDate": dt} 
    }); 

    counter++; 
    if (counter % 500 == 0) { 
     bulk.execute(); // Execute per 500 operations and re-initialize every 500 update statements 
     bulk = db.patient.initializeUnorderedBulkOp(); 
    } 
}) 
// Clean up remaining operations in queue 
if (counter % 500 != 0) { bulk.execute(); } 

下一個例子適用於新的MongoDB版本3.2這已經deprecated the Bulk API,並提供了新的一套使用bulkWrite()的API:

var bulkOps = db.patient.find({"birthDate": {"$exists": true, "$type": 2 }}).map(function (doc) { 
    var parts = doc.birthDate.split("-"); 
    var dt = new Date(
       parseInt(parts[0], 10), // year 
       parseInt(parts[1], 10) - 1, // month 
       parseInt(parts[2], 10) // day 
      ); 
    return { 
     "updateOne": { 
      "filter": { "_id": doc._id } ,    
      "update": { "$set": { "birthDate": dt } } 
     }   
    };   
}) 

db.patient.bulkWrite(bulkOps); 
+1

非常感謝它的工作...... :) – RAFA

2
db.collection.find().forEach(function(e){ 
e.fieldname = new Date(e.fieldname) 
db.collection.save(e) 
}); 

如果您正在使用robomonogo使用新ISODate而不是新的日期,你可以採取在現場轉換爲正確的日期對象