Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 844
Geek Avatar asked Oct 23 '25 14:10

Geek


1 Answers

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);
}
like image 67
s7vr Avatar answered Oct 26 '25 03:10

s7vr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!