Java 如何在mongo中插入带有日期的文档?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24483727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:28:59  来源:igfitidea点击:

How to insert a document with date in mongo?

javaeclipsemongodbmongodb-query

提问by itaied

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. We want to execute the Date()command of mongo to get the date from mongo and not from java.

我们正在尝试插入一个以当前日期作为字段的文档。我们正在使用 mongodb 的 eclipse 插件用 java 编写。我们要执行Date()mongo的命令以从 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

我在预览问题中发现了这个问题,但答案没有帮助

Link

关联

采纳答案by Neil Lunn

The standard driver takes java.util.datetypes and serializes as BSON dates. So with a collection object to "example"

标准驱动程序采用java.util.date类型并将其序列化为 BSON 日期。所以用一个集合对象来“示例”

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 $currentDateoperator, 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 _idor something equally unique.

由于这实际上是一条更新语句,因此如果您仅打算将其用作插入,则您需要注意实际上并未匹配任何文档。因此,最好确保您的“查询”包含独特的信息,例如新生成的_id或同样独特的信息。

回答by Devesh Kumar

Use this:

用这个:

db.example.insert({"date":new Date(Date.now())});

回答by maikelsperandio

You can do it trying something like this:

你可以尝试这样的事情:

db.example.insert({"date":ISODate("2016-03-03T08:00:00.000")});