Computer >> Máy Tính >  >> Lập trình >> MongoDB

Làm thế nào để chuyển đổi từ kiểu dữ liệu chuỗi sang ngày tháng trong MongoDB?

Để chuyển đổi từ kiểu dữ liệu Chuỗi sang ngày, bạn cần viết một số tập lệnh. Đầu tiên chúng ta hãy tạo bộ sưu tập bằng tài liệu

>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")
}

Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find ()

> db.stringToDateDataTypeDemo.find().pretty();

Điều này sẽ tạo ra kết quả sau

{
   "_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"
}

Sau đây là truy vấn để chuyển đổi kiểu dữ liệu Chuỗi thành ngày tháng

> db.stringToDateDataTypeDemo.find().forEach(function(data){
...    data.ShippingDate= ISODate(data.ShippingDate);
...    db.stringToDateDataTypeDemo.save(data);
... });

Hãy để chúng tôi hiển thị tất cả các tài liệu một lần nữa để kiểm tra chuỗi được chuyển đổi sang kiểu dữ liệu ngày tháng hay không. Sau đây là truy vấn

> db.stringToDateDataTypeDemo.find().pretty();

Điều này sẽ tạo ra kết quả sau

{
   "_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")
}