[英]How to insert a document with date in mongo?
We are trying to insert a document with the current date as it's field.我们正在尝试插入一个具有当前日期的文档作为它的字段。 We are writing in java using eclipse plugin for mongodb.
我们正在使用 mongodb 的 eclipse 插件在 java 中编写。 We want to execute the
Date()
command of mongo to get the date from mongo and not from java.我们想执行 mongo 的
Date()
命令来从 mongo 而不是从 java 中获取日期。
How can I execute this mongo query?如何执行这个 mongo 查询?
db.example.insert({"date":new Date()})
I found this question in a previews question but the answer was not helpful我在预览问题中发现了这个问题,但答案没有帮助
The standard driver takes java.util.date types and serializes as BSON dates.标准驱动程序采用java.util.date类型并序列化为 BSON 日期。 So with a collection object to "example"
所以用一个集合对象来“示例”
Date now = new Date();
BasicDBObject timeNow = new BasicDBObject("date", now);
example.insert(timeNow);
If you are looking for a way to use the "server" time in operations, there is the $currentDate
operator, but this works with "updates", so you would want an "upsert" operation:如果您正在寻找一种在操作中使用“服务器”时间的方法,可以使用
$currentDate
运算符,但这适用于“更新”,因此您需要一个“更新插入”操作:
BasicDBObject query = new BasicDBObect();
BasicDBObject update = new BasicDBObject("$currentDate",
new BasicDBObject("date", true)
);
example.update(query,update,true,false);
Since that actually is an update statement, you need to be careful that you are not actually matching any documents if you intend this to be an insert only.由于这实际上是一条更新语句,因此如果您打算将其仅用作插入,则需要注意您实际上并未匹配任何文档。 So it would be best to make sure your "query" contains unique information, such as a newly generated
_id
or something equally unique.因此,最好确保您的“查询”包含唯一信息,例如新生成的
_id
或同样唯一的信息。
你可以尝试这样的事情:
db.example.insert({"date":ISODate("2016-03-03T08:00:00.000")});
用这个:
db.example.insert({"date":new Date(Date.now())});
There is a key difference I noted when using Date() as follows.我在使用 Date() 时注意到了一个关键区别,如下所示。
{ dateWhenCreated : Date() }
vs对比
{ dateWhenCreated : new Date() }
Notice the "new" keyword in the second usage.注意第二种用法中的“new”关键字。 Whereas the first usage loads the data "as a string", the second one loads date as a field with date data type.
第一种用法将数据“作为字符串”加载,而第二种用法将日期加载为具有日期数据类型的字段。
This might impact your sorting capability - dates stored as strings don't get sorted the same way as dates stored as dates.这可能会影响您的排序能力 - 存储为字符串的日期的排序方式与存储为日期的日期不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.