如何在 MongoDB 中更新时间戳并设为当前日期?
要更新,请在 MongoDB 中使用 update()。要将其设为当前日期,你需要获取当前日期 −
var todayDate = new Date();
让我们首先创建一个带有文档的集合 −
> db.demo644.insertOne({"ShippingDate":new ISODate("2018-04-19")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c76896c954c74be91e6e6")
}
> db.demo644.insertOne({"ShippingDate":new ISODate("2019-01-10")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c76966c954c74be91e6e7")
}使用 find() 方法从集合中显示所有文档 −
> db.demo644.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e9c76896c954c74be91e6e6"), "ShippingDate" : ISODate("2018-04-19T00:00:00Z") }
{ "_id" : ObjectId("5e9c76966c954c74be91e6e7"), "ShippingDate" : ISODate("2019-01-10T00:00:00Z") }以下是更新时间戳的查询 −
> var todayDate = new Date();
> todayDate .setHours(todayDate.getHours() + 1);
1587315898453
> db.demo644.update({}, {$set: {ShippingDate:todayDate}}, {multi: true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })使用 find() 方法从集合中显示所有文档 −
> db.demo644.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e9c76896c954c74be91e6e6"), "ShippingDate" : ISODate("2020-04-19T17:04:58.453Z") }
{ "_id" : ObjectId("5e9c76966c954c74be91e6e7"), "ShippingDate" : ISODate("2020-04-19T17:04:58.453Z") }
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP