MongoDB 当 MongoTemplate 保留数据时截断 LocalDateTime 纳秒
MongoDB truncating LocalDateTime nanosecs when MongoTemplate persists the data
我有一个 Spring Boot 2 项目,使用 MongoDB 作为数据库。
当我通过调用 LocalDateTime.now() 实例化一个包含日期的对象作为 LocalDateTime 时;我收到一个包含纳秒的日期时间,其中有超过 4 个数字位。
当我使用 mongotemplate.save 在 mongoDB 中保存此数据时,保存的值仅包含纳秒的 3 个位置(其余填充为零)。那么,如何在存储到数据库时达到相同的精度?或者另一种选择:在 java?
中创建 LocalDateTime 实例时如何限制精度
@Document("Entity")
public class Entity implements Serializable {
@Id
private String id;
@Indexed(name = "created")
private LocalDateTime created;
public HistoryEntity(){
// This gives me 2020-01-30T13:25:09.817182
this.created = LocalDateTime.now();
}
}
@Repository
public class DAO {
@Autowired
private MongoTemplate mongoTemplate;
public void save(Entity e) {
// When value is persisted, I get 2020-01-30T13:25:09.817 if I look into mongoDB instance or if I retrieve the same entity from DB in Java
Entity saved = mongoTemplate.save(e);
}
}
我想我找到了答案,除了从 java 端截断我的 LocalDateTime 外,我可能无能为力(正如我在上一条评论中所解释的,如下所示)
Clock millisecondClock = Clock.tick(Clock.systemDefaultZone(), Duration.ofNanos(1000000));
LocalDateTime d = LocalDateTime.now(millisecondClock);
我正在阅读 Baeldung 的这篇文章 https://www.baeldung.com/spring-data-mongodb-zoneddatetime 时遇到以下陈述(回答了我的问题):
... we're removing the nanoseconds information since the MongoDB Date type has a precision of milliseconds:
就是这样。即使我想以更高的精度工作,似乎 MongoDB 无法处理(至少目前)
我有一个 Spring Boot 2 项目,使用 MongoDB 作为数据库。
当我通过调用 LocalDateTime.now() 实例化一个包含日期的对象作为 LocalDateTime 时;我收到一个包含纳秒的日期时间,其中有超过 4 个数字位。
当我使用 mongotemplate.save 在 mongoDB 中保存此数据时,保存的值仅包含纳秒的 3 个位置(其余填充为零)。那么,如何在存储到数据库时达到相同的精度?或者另一种选择:在 java?
中创建 LocalDateTime 实例时如何限制精度@Document("Entity")
public class Entity implements Serializable {
@Id
private String id;
@Indexed(name = "created")
private LocalDateTime created;
public HistoryEntity(){
// This gives me 2020-01-30T13:25:09.817182
this.created = LocalDateTime.now();
}
}
@Repository
public class DAO {
@Autowired
private MongoTemplate mongoTemplate;
public void save(Entity e) {
// When value is persisted, I get 2020-01-30T13:25:09.817 if I look into mongoDB instance or if I retrieve the same entity from DB in Java
Entity saved = mongoTemplate.save(e);
}
}
我想我找到了答案,除了从 java 端截断我的 LocalDateTime 外,我可能无能为力(正如我在上一条评论中所解释的,如下所示)
Clock millisecondClock = Clock.tick(Clock.systemDefaultZone(), Duration.ofNanos(1000000));
LocalDateTime d = LocalDateTime.now(millisecondClock);
我正在阅读 Baeldung 的这篇文章 https://www.baeldung.com/spring-data-mongodb-zoneddatetime 时遇到以下陈述(回答了我的问题):
... we're removing the nanoseconds information since the MongoDB Date type has a precision of milliseconds:
就是这样。即使我想以更高的精度工作,似乎 MongoDB 无法处理(至少目前)