[英]Find and change existing date field formats in MongoDB
I've looked into several similar questions but none seem to be what I need, aside from looking complicated.我已经研究了几个类似的问题,但除了看起来很复杂之外,似乎没有一个是我需要的。 Here's the scenario: I have a messy collection with multiple "date" fields, with names I already know (eg "dateTime", "FirstDate", "Status.date"...).
这是场景:我有一个包含多个“日期”字段的凌乱集合,其中的名称我已经知道(例如“dateTime”、“FirstDate”、“Status.date”......)。
For each of them, I would like to:对于他们每个人,我想:
The company I work in unfortunately uses a free edition of NoSQLBooster, in Version 6.2.13.不幸的是,我工作的公司使用 NoSQLBooster 的免费版本,版本为 6.2.13。 From what I could see, it has many limited capabilities, so please keep that in mind.
据我所知,它有许多有限的功能,所以请记住这一点。 Is it possible to do this?
是否有可能做到这一点? Any help will be much appreciated!
任何帮助都感激不尽!
You can do the following steps:您可以执行以下步骤:
$ifNull
to choose the date field from your list of known field names$ifNull
从已知字段名称列表中选择日期字段$dateFromString
$dateFromString
在所选字段上尝试两种类型的日期解析('dd/mm/YYYY' 或 'YYYY-mm-dd')$out
to output the final result to some collection for your future processing$out
将最终结果输出到某个集合以供您将来处理Here is the Mongo playground for your reference.这是Mongo游乐场供您参考。
Sharing my approach for posterity, I have come across a similar situation, where I need to update my collection's date format from String to date for the known fields, I have done the below approach for the update分享我的后代方法,我遇到了类似的情况,我需要将我的集合的日期格式从字符串更新为已知字段的日期,我已经完成了以下更新方法
For instance, I have date fields such as datefield1
and datefield2
in String format which I need to change into date format例如,我有字符串格式的
datefield1
和datefield2
等日期字段,我需要将其更改为日期格式
db.getCollection('collection_name').updateMany({ $or: [{ "datefield1": { '$type': "string"} },
{ "datefield2": { '$type': "string"} }] }
, [
{ "$addFields": {
"datefield1": {
"$toDate": "$datefield1"
}
} },
{ "$addFields": {
"datefield2": {
"$toDate": "$datefield2"
}
} }
])
In the above case, my existing date string was a proper ISO format "2020-12-03T10:06:53.502Z"
, hence I used the $toDate
, in case of custom/ different date format follow the below approach在上述情况下,我现有的日期字符串是正确的 ISO 格式
"2020-12-03T10:06:53.502Z"
,因此我使用了$toDate
,如果是自定义/不同的日期格式,请遵循以下方法
db.getCollection('collection_name').updateMany({ $or: [{ "datefield1": { '$type': "string"} },
{ "datefield2": { '$type': "string"} }] }
, [
{ "$addFields": {
"datefield1": {
"$dateFromString": {
"dateString": "$datefield1",
"format": "%Y-%m-%dT%H:%M:%S.%LZ"
}
}
}
}, { "$addFields": {
"datefield2": {
"$dateFromString": {
"dateString": "$datefield2",
"format": "%Y-%m-%dT%H:%M:%S.%LZ"
}
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.