首页 > 解决方案 > Convert string to date in pymongo

问题描述

Using Community MongoDB 4.4.3, I have a sample test collection:

client = pymongo.MongoClient('localhost', 27017)
db = client.test
collection = db.test_collection
print(collection.find_one())

>>> {'_id': ObjectId('600d8e2f4cf39c04cdb86ea0'),
 'id': '0706.1314',
 'update_date': '2008-12-18'}

I'm trying to convert string to date for the field update_date with $toDate operator:

collection.aggregate([{"$toDate": "update_date"}])

But get the following error:

OperationFailure: Unrecognized pipeline stage name: '$toDate', full error: {'ok': 0.0, 'errmsg': "Unrecognized pipeline stage name: '$toDate'", 'code': 40324, 'codeName': 'Location40324'}

Why does this happen?

标签: mongodbpython-3.6pymongo

解决方案


您需要指定输入字段,如下所示:

 collection.aggregate([  {$project:{ newField:{"$toDate": "$update_date"}}}       ])

推荐阅读