[英]Pymongo convert timestamp to date as a new field
我的集合中有很多實體,我必須在集合中創建一個新的日期字段以用於將來的查詢。
{'_id': ObjectId('5afea920d326051990a7f337'), 'created_at': 'Fri May 18 10:21:07 +0000 2018', 'timestamp_ms': '1526638867739'}
{'_id': ObjectId('5afea920d326051990a7f339'), 'created_at': 'Fri May 18 10:21:08 +0000 2018', 'timestamp_ms': '1526638868310'}
{'_id': ObjectId('5afea972d326051c5c05bc11'), 'created_at': 'Fri May 18 10:22:30 +0000 2018', 'timestamp_ms': '1526638950799'}
{'_id': ObjectId('5afea974d326051c5c05bc16'), 'created_at': 'Fri May 18 10:22:32 +0000 2018', 'timestamp_ms': '1526638952160'}
{'_id': ObjectId('5afea974d326051c5c05bc17'), 'created_at': 'Fri May 18 10:22:32 +0000 2018', 'timestamp_ms': '1526638952841'}
我需要將timestamp_ms轉換為日期格式,如下所示:
{'_id': ObjectId('5afea920d326051990a7f337'), 'created_at': 'Fri May 18 10:21:07 +0000 2018', 'timestamp_ms': '1526638867739’, 'NewDate': '2018 05 18 10:21:07'}
{'_id': ObjectId('5afea920d326051990a7f339'), 'created_at': 'Fri May 18 10:21:08 +0000 2018', 'timestamp_ms': '1526638868310’, 'NewDate': '2018 05 18 10:21:08'}
{'_id': ObjectId('5afea972d326051c5c05bc11'), 'created_at': 'Fri May 18 10:22:30 +0000 2018', 'timestamp_ms': '1526638950799’, 'NewDate': '2018 05 18 10:22:30'}
{'_id': ObjectId('5afea974d326051c5c05bc16'), 'created_at': 'Fri May 18 10:22:32 +0000 2018', 'timestamp_ms': '1526638952160’, 'NewDate': '2018 05 18 10:22:32'}
{'_id': ObjectId('5afea974d326051c5c05bc17'), 'created_at': 'Fri May 18 10:22:32 +0000 2018', 'timestamp_ms': '1526638952841’, 'NewDate': '2018 05 18 10:22:32'}
我使用了這段代碼(Python 3.6,pymongo 3.8,mongodb 4.0):
pipeline = [
{
'$addFields': {
'newDate': {
'$toDate': '$timestamp_ms'
}
}
}
]
cursor = collection.aggregate(pipeline)
但是給出了以下錯誤消息: pymongo.errors.OperationFailure: Error parsing date string '1526638867739'; 12: Unexpected character '9'
pymongo.errors.OperationFailure: Error parsing date string '1526638867739'; 12: Unexpected character '9'
我不確定聚合是否是執行此任務的正確方法。 datetime.strptime()
對於'created_at'
可能更好,但我還沒想出如何將它實現到db.Mycollection_update_many()
。
使用下面的查詢與pymongo和mongodb 4.0
db.test.aggregate(
[
{
"$addFields": {
"NewDate": {"$toDate": "$timestamp_ms"}
}
},
{
"$out": "test"
},
],
)
我從MongoDB大學討論論壇的Kanika Singla那里得到了我的問題答案。 答案就在這里,如果你有同樣的問題。
pipeline = [
{
'$project': {
'yearMonthDayUTC': {
'$convert': {
'to': 'double',
'input': '$timestamp_ms'
}
}
}
}, {
'$addFields': {
'newDate': {
'$toDate': '$yearMonthDayUTC'
}
}
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.