Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

mongodb - 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?

question from:https://stackoverflow.com/questions/65873085/convert-string-to-date-in-pymongo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you need to specify the input field as follow:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...