I am having a problem handling dates between my java server and mongodb. I am using Spring Data with MongoDB. My java code is deployed in Tomcat on a linux environment.
I have verified that the server time on my Java linux box is the same as the linux box on which MongoDB is running.
A simple example to find an object gives me a discrepancy in the last modified date field.
public Note getNoteById(String noteId) {
Query q = new Query().addCriteria(Criteria.where("_id").is(noteId));
return mongoTemplate.findOne(q, Note.class);
}
In the Note class, I have a last modified field which is a java Date. However, when I retrieve the java object, I see that the last modified date is 6-7 hours different from the Database value.
#Document(collection = "notes")
public class Note {
#Indexed
private String id;
private String title;
private Date lastModifiedDate;
...
The database value for the last modified date field is ISODate("2016-05-09T18:51:02.000Z"). However, when I read the Note document in Java, I see that the Note object in Java has a date of Mon May 09 11:51:02 PDT 2016 which is 7 hours different from the DB value.
Can you please help?
Related
Update
Ockham's razor sliced through this problem.
Turns out the issue was:
Document did not have an _id field
#Id
private String id;
So the update() method would insert a new record rather than update existing record.
the 'find' code used 'findOne()'
for some reason findOne() appeared to behave differently in different environemts (i.e. in local dev environments it would retrieve 'most recent', but on our server environment , retrieved the 'oldest'.). Whatever something in local env masked the problem.
TLDR
'save and immediate retrieve' mongodb document with embedded document (i.e. field w/ java object/json) does not show expected updates
problem appears intermittently and only on some environments
Background
I'm new to mongo so don't know the tricks/techniques/gotchas/etc.. I'm versed in relationaldb and transactions, so this error threw me.
for better or worse, I designed a mongo collection that looks like this:
#Document
public class BidOffers {
...
// note 'Suppliers' here is plural, ie. offers from multiple suppliers
SuppliersOffers offers;
where SuppliersOffers object simply has a list of SupplierOffer objects
public class SuppliersOffers {
List<SupplierOffer> offers = new ArrayList<>();
and SupplierOffer just has a 'supplier code' and a price
public class SupplierOffer {
String supplierCode
BigDecimal price
}
Usecase
In this usecase:
Retrieve document BidOffers from mongodb
Note that document has only one offer
Add a new offer to the list
Save document
Print saved document to log, i.e. and note/confirm "saved document now has two offers in list, not just one"
Some (short) time later (i.e. in the same thread) retrieve the document
Expected Results
retrieved document has two offers
Actual Result
retrieve document has only one offer
More details
Java 8
Spring Boot 2.x
Problem appears on Mongodb 4.0 version (AWS Managed Service)
Problem appears regularly, but not 100% consistently
I do not see this problem when testing locally (Mongdb 3.6.8)
I want to delete QA database older than 2 months in mongodb using reactiveMongoRepository using spring web flux, how can I do that, do I have to create a custom query a custom method can work. I have class in which particular fields are there
class A { private String Id;
private String title;
private Instant startTime;
private Instant endTime;
}
I am not getting idea how to work on that
I want to save date in Timestamp format in couchbase database using spring boot application.
I have tried this but getting exception while retrieving date from couchbase.
Here is my code:
POJO:
public class Request {
private Timestamp createDate;
private Timestamp updateDate;
}
Taken in POJO.
saving into db:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
urxRequest.setCreateDate(timestamp);
here it is saving date as a long so while retrieving I am getting cast exception.. can not cast from long to Date..
Please help me for this.
I would like my MongoRepository in Spring Boot to automatically delete documents at a certain point in time after creation. Therefore I created the following class:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
public class MyDocument {
#Id
private String id;
#Indexed
private String name;
#Indexed(expireAfterSeconds = 0)
private LocalDateTime deleteAt;
}
Then, I save it in the Spring Boot MongoRepository:
MyDocument doc = modelMapper.map(myDocumentDto, MyDocument.class);
LocalDateTime timePoint = LocalDateTime.now();
timePoint = timePoint.plusMinutes(1L);
doc.setDeleteAt(timePoint);
docRepository.save(doc);
I periodically query the repository and would assume that after one minute, the document will not be there anymore. Unfortunately, I get the document every time I query and it is never deleted.
What am I doing wrong?
The document is persisted as follows (.toString()):
MyDocument{id='5915c65a2e9b694ac8ff8b67', name='string', deleteAt=2017-05-12T16:28:38.787}
Is MongoDB possibly unable to read and process the LocalDateTime format? I'm using org.springframework.data:spring-data-mongodb:1.10.1.RELEASE, so JSR-310 should already be supported as announced in 2015 here: https://spring.io/blog/2015/03/26/what-s-new-in-spring-data-fowler
I could fix the issue:
First of all, java.time.LocalDateTime is no problem with Spring Data / MongoDB.
For clarification, add a name to an index, e.g. #Indexed(name = "deleteAt", expireAfterSeconds = 0). This step might not be needed though. However, adding the #Document annotation helped a lot:
#Document(collection = "expiringDocument")
When I delete the whole collection while my application is running, a new document insert will create the collection again but without the indexes. To ensure indexes are created, restart the application.
I have one model with DateUpdated DateTime property.
Before i update that model, my model information's are
After i update my model information's are
Why MongoDB store wrong DateUpdated value? I tried several times with debugger, and looks like every time that value is changed but with wrong DateTime.
Im using C# Driver.
My Update function is
var query = Query.EQ("_id", p.UserID);
var update = MongoDB.Driver.Builders.Update.Replace(p);
SafeModeResult success = MongoRepository.Profiles().Update(query, update);
SafeModeResult is always success.
My DateUpdated Bson property is
[BsonElement("da")]
[BsonDateTimeOptions(Representation = BsonType.Document)]
public DateTime DateUpdated{ get; set; }
MongoDB stores DateTime values in UTC. What you are seeing is the conversion of local time to UTC.
The best way to handle timezones is to keep all your data in UTC (including in your data model, not just the database) and only convert to local time at the point you display a value to the user.