Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 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 Answer

0 votes
by (71.8m points)

you need to specify the input field as follow:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...