在 MongoDB 中将字符串转换为日期?(已翻译)
若要在 MongoDB 中将字符串转换为日期,请使用以下语法
db.yourCollectionName.aggregate( [ { $project: { anyVariableName: { $dateFromString: { dateString: '$yourFieldName’ } } } } ] );
为了理解以上的语法,我们来创建一个包含一些文档的集合。下为用于创建包含文档的集合的查询
> db.ConvertStringToDateDemo.insertOne({"ArrivalDate":"20-10-2019"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef3596fd07954a489069f") } > db.ConvertStringToDateDemo.insertOne({"ArrivalDate":"21-02-2019"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef3616fd07954a48906a0") } > db.ConvertStringToDateDemo.insertOne({"ArrivalDate":"10-12-2018"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef36d6fd07954a48906a1") } > db.ConvertStringToDateDemo.insertOne({"ArrivalDate":"31-01-2017"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef37b6fd07954a48906a2") }
使用 find() 方法显示集合中的所有文档。查询如下
> db.ConvertStringToDateDemo.find().pretty();
以下是输出
{ "_id" : ObjectId("5c6ef3596fd07954a489069f"), "ArrivalDate" : "20-10-2019" } { "_id" : ObjectId("5c6ef3616fd07954a48906a0"), "ArrivalDate" : "21-02-2019" } { "_id" : ObjectId("5c6ef36d6fd07954a48906a1"), "ArrivalDate" : "10-12-2018" } { "_id" : ObjectId("5c6ef37b6fd07954a48906a2"), "ArrivalDate" : "31-01-2017" }
以下是将字符串转换为日期的查询
> db.ConvertStringToDateDemo.aggregate( [ { ... $project: { ... StringToDate: { ... $dateFromString: { ... dateString: '$ArrivalDate' ... } ... } ... } ... } ] ).pretty();
以下是输出
{ "_id" : ObjectId("5c6ef3596fd07954a489069f"), "StringToDate" : ISODate("2019-10-20T00:00:00Z") } { "_id" : ObjectId("5c6ef3616fd07954a48906a0"), "StringToDate" : ISODate("2019-02-21T00:00:00Z") } { "_id" : ObjectId("5c6ef36d6fd07954a48906a1"), "StringToDate" : ISODate("2018-12-10T00:00:00Z") } { "_id" : ObjectId("5c6ef37b6fd07954a48906a2"), "StringToDate" : ISODate("2017-01-31T00:00:00Z") }
广告