如何在mongo中插入带有日期的文档? [英] How to insert a document with date in mongo?

查看:143
本文介绍了如何在mongo中插入带有日期的文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试将当前日期的文档作为字段插入。我们正在使用eclipse插件为mongodb编写。我们要执行mongo的 Date()命令,以从mongo而不是从java获取日期。

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.

如何执行这个mongo查询?

How can I execute this mongo query?

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

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

I found this question in a previews question but the answer was not helpful

链接

推荐答案

标准驱动程序需要 java.util.date 类型并序列化为BSON日期。所以用示例的集合对象

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

Date now = new Date();

BasicDBObject timeNow = new BasicDBObject("date", now);
example.insert(timeNow);

如果您正在寻找一种在运营中使用服务器时间的方法, a href =http://docs.mongodb.org/manual/reference/operator/update/currentDate/#up._S_currentDate> $ currentDate 操作符,但这适用于更新,因此您需要一个upsert操作:

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:

 BasicDBObject query = new BasicDBObect();
 BasicDBObject update = new BasicDBObject("$currentDate",
     new BasicDBObject("date", true)
 );

 example.update(query,update,true,false);

由于实际上是一个更新语句,您需要注意,您实际上并不匹配任何文档如果你打算这样做只是一个插入。所以最好确保你的查询包含唯一的信息,例如新生成的 _id 或同样唯一的东西。

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.

这篇关于如何在mongo中插入带有日期的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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