【问题标题】:MongoDB type a attribute of document in collectionMongoDB在集合中键入文档的属性
【发布时间】:2022-02-05 21:41:05
【问题描述】:
我目前正在从事一个将定期数据保存到 MongoDB 数据库的项目。
在这个数据库中,我有几个元素,每个文档都包含日期。
有问题
文档包含错误的日期属性类型。
这是由于插入错误,所有文档都有字符串格式的日期。
我可以使用 MongoDB Atlas 图形界面更新每个属性,但是这个解决方案太长了..
问题
我想知道在 MongoDB 中我们是否有一个解决方案来更新集合中所有文档的属性类型。
【问题讨论】:
标签:
mongodb
mongodb-atlas
【解决方案1】:
如果我理解正确,你可以试试这些:
db.collection.aggregate([
{ "$addFields": {
"date": {
"$toDate": "$date"
}
} }
])
db.collection.aggregate([
{ "$addFields": {
"date": {
"$convert": {
"input": "$date",
"to": "date"
}
}
} }
])
db.collection.aggregate([
{ "$addFields": {
"date": {
"$dateFromString": {
"dateString": "$date",
"format": "%m-%d-%Y"
}
}
} }
])
var bulkOps = [];
var cursor = db.collection.find({});
cursor.forEach(function (doc) {
var newDate = new ISODate(doc.date);
bulkOps.push(
{
"updateOne": {
"filter": { "_id": doc._id },
"update": { "$set": { "date": newDate } }
}
}
);
});
if (bulkOps.length > 0) {
db.collection.bulkWrite(bulkOps);
}
【解决方案2】:
对于您的情况,最简单的解决方案是在使用聚合管道的更新中使用 $toDate
db.collection.update({},
[
{
"$addFields": {
"date": {
"$toDate": "$date"
}
}
}
])
这是Mongo playground 供您参考。
如果需要配合其他日期格式,可以使用$dateFromString。
db.collection.update({},
[
{
"$addFields": {
"date": {
"$dateFromString": {
"dateString": "$date",
"format": <your format here>
}
}
}
}
])
格式解析器可以参考$dateFromString上的this official documentation。