要将String从String转换为date数据类型,您需要编写一些脚本。首先让我们创建一个包含文档的集合
>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") }