如何在 MongoDB 中将字符串转换为日期数据类型?
要将字符串转换为日期数据类型,你需要编写一些脚本。让我们首先创建一个包含文档的集合
>db.stringToDateDataTypeDemo.insertOne({"CustomerName":"Carol","ShippingDate":"2019- 01-21"}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2071d66324ffac2a7dc60") } >db.stringToDateDataTypeDemo.insertOne({"CustomerName":"Bob","ShippingDate":"2019- 02-24"}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2073566324ffac2a7dc61") } >db.stringToDateDataTypeDemo.insertOne({"CustomerName":"Chris","ShippingDate":"2019- 04-01"}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2074266324ffac2a7dc62") }
以下是使用 find() 方法从集合显示所有文档的查询
> db.stringToDateDataTypeDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5ca2071d66324ffac2a7dc60"), "CustomerName" : "Carol", "ShippingDate" : "2019-01-21" } { "_id" : ObjectId("5ca2073566324ffac2a7dc61"), "CustomerName" : "Bob", "ShippingDate" : "2019-02-24" } { "_id" : ObjectId("5ca2074266324ffac2a7dc62"), "CustomerName" : "Chris", "ShippingDate" : "2019-04-01" }
以下是将 String 转换为日期数据类型的查询
> db.stringToDateDataTypeDemo.find().forEach(function(data){ ... data.ShippingDate= ISODate(data.ShippingDate); ... db.stringToDateDataTypeDemo.save(data); ... });
让我们再次显示所有文档,以检查字符串是否已转换为日期数据类型。以下为查询
> db.stringToDateDataTypeDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5ca2071d66324ffac2a7dc60"), "CustomerName" : "Carol", "ShippingDate" : ISODate("2019-01-21T00:00:00Z") } { "_id" : ObjectId("5ca2073566324ffac2a7dc61"), "CustomerName" : "Bob", "ShippingDate" : ISODate("2019-02-24T00:00:00Z") } { "_id" : ObjectId("5ca2074266324ffac2a7dc62"), "CustomerName" : "Chris", "ShippingDate" : ISODate("2019-04-01T00:00:00Z") }
广告