Geek
Geek

Reputation: 1344

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.

Upvotes: 4

Views: 25703

Answers (2)

j9dy
j9dy

Reputation: 2179

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.

Upvotes: 0

s7vr
s7vr

Reputation: 75934

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);
}

Upvotes: 6

Related Questions