简体   繁体   English

Java到Mongo的文档日期

[英]Java to Mongo Document date

I am inserting a document by converting the pojo to document object using static parse method from Mongo driver. 我通过使用Mongo驱动程序中的静态解析方法将pojo转换为文档对象来插入文档。

Document newList = parse(gson.toJson(myPoJo));
collections.insertOne(newList);

This pojo has a Date attribute. 此pojo具有Date属性。 But parse method will not adhere this type and convert it to string i think. 但是解析方法不会坚持这种类型并将其转换为字符串,我认为。 So after insert my document is something like below. 因此,插入后,我的文档如下所示。

 { "auditInfo" : {
        "updatedDate" : "Feb 28, 2000 3:39:20 PM",
   } 
}

Problem with this is i wont be able to perform date comparison in mongo query. 问题是我无法在mongo查询中执行日期比较。

Please advise on how to handle this. 请告知如何处理。

You can try something like below. 您可以尝试以下类似方法。

Using Mongo Java Driver: 使用Mongo Java驱动程序:

 MongoClient mongoClient = new MongoClient();
 MongoDatabase db = mongoClient.getDatabase("test");
 MongoCollection col = db.getCollection("input");

 Input input = new Input();
 input.setName("name");
 input.setDate(new Date());

 Document doc = new Document();
 doc.append("name", input.getName());
 doc.append("date", input.getDate())

 col.insertOne(doc);

Using Morphia 使用Morphia

Morphia takes care of validating & mapping mongo data to and from request and response. Morphia负责验证mongo数据与请求和响应之间的映射关系。

Pojo: POJO:

package org.mongodb.morphia;
import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import java.io.Serializable;
import java.util.Date;

@Entity("input")
public class Input implements Serializable {
    @Id
    private ObjectId id;

    private String name;

    private Date date;
}

Main: 主要:

public class MorphiaClient {
  public static void main(String[] args) {
    final Morphia morphia = new Morphia();
    morphia.mapPackage("org.mongodb.morphia");
    final Datastore datastore = morphia.createDatastore(new MongoClient(), "test");
    Input input = new Input();
    input.setName("name");
    input.setDate(new Date());
    datastore.save(input);
}

As outlined in the java driver documentation , the driver accepts a variety of commonly used java types and converts these into the corresponding BSON types internally. Java驱动程序文档中所述,驱动程序接受各种常用的Java类型并将其内部转换为相应的BSON类型。 You must pass objects of these supported types for this to work though. 但是,您必须传递这些受支持类型的对象才能使它起作用。

The value of your field updatedDate must be of type java.util.Date . 您的字段updatedDate的值必须为java.util.Date类型。 The java driver will then be able to convert it to the correct type, org.bson.BsonDateTime , afterwards. 之后,Java驱动程序将能够将其转换为正确的类型org.bson.BsonDateTime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM