插入时在MongoDB中自动填充日期 [英] Auto populate date in MongoDB on insert

查看:154
本文介绍了插入时在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):

  1. 如果你想使用 $currentDate 使用 update with upsert = true:

  1. 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).

  1. 直接使用新的时间戳或日期对象:

  1. 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.

这篇关于插入时在MongoDB中自动填充日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆