简体   繁体   中英

Java to Mongo Document date

I am inserting a document by converting the pojo to document object using static parse method from Mongo driver.

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

This pojo has a Date attribute. 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.

Please advise on how to handle this.

You can try something like below.

Using Mongo Java Driver:

 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 takes care of validating & mapping mongo data to and from request and response.

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. 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 . The java driver will then be able to convert it to the correct type, org.bson.BsonDateTime , afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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