我有以下收藏
/* 1 */
{
"_id" : ObjectId("5ceb7e71636566fe7718733e"),
"project_name" : "p1",
"expected" : "19-Sep-2019",
"actual" : "19-Sep-2019"
}
/* 2 */
{
"_id" : ObjectId("5ceb7e71636566fe77187340"),
"project_name" : "p2",
"expected" : "20-Sep-2019",
"actual" : "20-Sep-2019"
},
{
"_id" : ObjectId("5ceb7e71636566fe77187340"),
"project_name" : "p2",
"actual" : "20-Sep-2019"
},
{
"_id" : ObjectId("5ceb7e71636566fe77187340"),
"project_name" : "p2",
"expected" : "",
"actual" : "20-Sep-2019"
}
我需要以YYYY-MM-DD格式更新期望和实际的2个字段。如何为此编写更新查询?
使用MongoDB V4.0
,由于这是一次性操作,因此您可以尝试以下操作:
db.collection.aggregate([
{
$addFields: {
expected: {
$cond: [
{
$and: [
{
$ne: [
"$expected",
""
]
},
{
$ne: [
{
$type: "$expected"
},
"missing"
]
}
]
},
{
$dateToString: {
format: "%Y-%m-%d",
date: {
$dateFromString: {
dateString: "$expected"
}
}
}
},
""
]
},
actual: {
$cond: [
{
$and: [
{
$ne: [
"$actual",
""
]
},
{
$ne: [
{
$type: "$actual"
},
"missing"
]
}
]
},
{
$dateToString: {
format: "%Y-%m-%d",
date: {
$dateFromString: {
dateString: "$actual"
}
}
}
},
""
]
}
}
}, { $out: "collection_new" }
])
测试: MongoDB-操场
注意:您需要注意$ out,在此阶段,输入名称应与任何现有集合名称都不匹配,如果这样做会丢弃该集合并使用聚合结果重新创建它,如果您需要重新执行此过程时间使用$ merge而不是$out
。同样,一旦您输入了正确的数据,collection_new
就可以删除现有数据collection
并将新集合重命名为旧名称。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句