如何在MongoDB中将对象数组的字符串类型替换为日期类型?
我知道转换第一级日期的方法如何在MongoDB中将对象数组的字符串类型替换为日期类型?,mongodb,Mongodb,我知道转换第一级日期的方法 db.collection.find().forEach(function(x){ x.DateField = ISODate(x.DateField); db.collection.save(x);}) 这适用于一级字段,但是如果我想更改以下json示例中数组中对象的字段,例如CreatedTime,我应该怎么做: { "Pharmacy": "b", "Medicine": [ { "MedName": "MedB
db.collection.find().forEach(function(x){
x.DateField = ISODate(x.DateField);
db.collection.save(x);})
这适用于一级字段,但是如果我想更改以下json示例中数组中对象的字段,例如CreatedTime
,我应该怎么做:
{
"Pharmacy": "b",
"Medicine": [
{
"MedName": "MedB",
"Quantity": 60,
"CreatedTime" : "2006-05-05T11:44:47.86Z"
},
{
"MedName": "MedC",
"Quantity": 34,
"CreatedTime" : "2006-11-23T12:28:44.86Z"
}
]
}
编辑:=======第二种方法:
编辑:=======第二种方法:
您可以使用聚合查询和批量更新中的光标来更新4.0版本中的文档 与一起使用可保留现有值并将字符串日期转换为日期类型 这是贝壳样品
var bulk = db.collection.initializeUnorderedBulkOp();
var count = 0;
var batch = 50; // Change batch size as you need
db.collection.aggregate([
{"$project":{
"Medicine":{
"$map":{
"input":"$Medicine",
"in":{
"MedName":"$$this.MedName",
"Quantity":"$$this.Quantity",
"CreatedTime":{"$toDate":"$$this.CreatedTime"}
}
}
}
}}
]).forEach(function(doc){
bulk.find( {"_id" : doc._id}).updateOne(
{ "$set": {"Medicine" : doc.Medicine}}
);
count++;
if (count == batch) {
bulk.execute();
bulk = db.collection.initializeUnorderedBulkOp();
count = 0;
}
});
if (count > 0) {
bulk.execute();
}
您可以使用聚合查询和批量更新中的光标来更新4.0版本中的文档 与一起使用可保留现有值并将字符串日期转换为日期类型 这是贝壳样品
var bulk = db.collection.initializeUnorderedBulkOp();
var count = 0;
var batch = 50; // Change batch size as you need
db.collection.aggregate([
{"$project":{
"Medicine":{
"$map":{
"input":"$Medicine",
"in":{
"MedName":"$$this.MedName",
"Quantity":"$$this.Quantity",
"CreatedTime":{"$toDate":"$$this.CreatedTime"}
}
}
}
}}
]).forEach(function(doc){
bulk.find( {"_id" : doc._id}).updateOne(
{ "$set": {"Medicine" : doc.Medicine}}
);
count++;
if (count == batch) {
bulk.execute();
bulk = db.collection.initializeUnorderedBulkOp();
count = 0;
}
});
if (count > 0) {
bulk.execute();
}
@Acex,这是测试过的查询。等等,什么是允许我读取字符串作为日期的运算符?抱歉?没有找到您。您的
CreatedTime
位于字符串中。您只需迭代每个文档,获取所有String
date,然后将date分配给CreatedTime
。然后保存它。它会将您的字符串
日期更改为日期
对象您删除的第二种方法实际上对我更有帮助。虽然它没有回答这个问题completely@Acex,这是已测试的查询。等等,允许我读取字符串作为日期的运算符是什么?抱歉?没有找到您。您的CreatedTime
位于字符串中。您只需迭代每个文档,获取所有String
date,然后将date分配给CreatedTime
。然后保存它。它会将您的字符串
日期更改为日期
对象您删除的第二种方法实际上对我更有帮助。虽然它不能完全回答这个问题
var bulk = db.collection.initializeUnorderedBulkOp();
var count = 0;
var batch = 50; // Change batch size as you need
db.collection.aggregate([
{"$project":{
"Medicine":{
"$map":{
"input":"$Medicine",
"in":{
"MedName":"$$this.MedName",
"Quantity":"$$this.Quantity",
"CreatedTime":{"$toDate":"$$this.CreatedTime"}
}
}
}
}}
]).forEach(function(doc){
bulk.find( {"_id" : doc._id}).updateOne(
{ "$set": {"Medicine" : doc.Medicine}}
);
count++;
if (count == batch) {
bulk.execute();
bulk = db.collection.initializeUnorderedBulkOp();
count = 0;
}
});
if (count > 0) {
bulk.execute();
}