插入时在MongoDB中自动填充日期
MongoDB 提供了一种系统在更新操作时更新日期字段的方法:https://docs.mongodb.com/manual/reference/operator/update/currentDate/.插入操作有什么等价的吗?
MongoDB provides a way to update a date field by the system on update operations: https://docs.mongodb.com/manual/reference/operator/update/currentDate/. Is there any equivalent to this for insert operations?
如果你不想从代码中处理这个,你可以尝试做一些事情(我已经直接在 mongo shell 上执行了下面的代码):>
You may try to do a few things if you do not want to handle this from code (I have executed the code below directly on mongo shell):
如果你想使用 $currentDate 使用 update with upsert = true:
If you want to use $currentDate use update with upsert = true:
db.orders.update(
{"_id":ObjectId()},
{
$currentDate: {
createtime: true
}
},
{ upsert: true }
)
它现在将在应用服务器上生成 objectid 而不是日期/时间(除非您使用原始命令).
It will now generate the objectid on app server instead of date/time (unless you use raw command).
直接使用新的时间戳或日期对象:
Use new timestamp or date object directly:
db.orders.insert(
"createtime": new Timestamp()
)
大多数驱动程序的问题是确保新对象是在 mondodb 服务器上创建的,而不是在运行代码的机器上.您的驱动程序希望允许运行原始插入命令.
The problem with most driver will be then to make sure the new object is created on mondodb server- not on the machine where the code is running. You driver hopefully allows to run raw insert command.
两者都将有助于避免应用服务器机器之间的时间差异/时间同步问题.
Both will serve the purpose of avoiding time differences/ time sync issue between application server machines.