I develop a Spring Application which saves JSON in MongoDb. The client is able to search for data with entering a time interval begin and end. To be able to use regex (lte and gte) to get the data from the database I save the Time as UnixTimeStamp:
"TimeStamp": {
"StartTime": 1549371540000,
"EndTime" : 1549371540000,
"StartTimeZone":"Europe/Berlin",
"EndTimeZone":"Europe/Berlin"
}
The filtering works but I get the following as a result:
"TimeStamp": {
"StartTimeZone": "Europe/Berlin",
"EndTimeZone": "Europe/Berlin",
"EndTime": {
"$numberLong": "1549371540000"
},
"StartTime": {
"$numberLong": "1549371540000"
}
}
Is it possible to just get the key-value pair instead of the StartTime Object with the $numberLong key? I was also thinking about saving the time aso Iso format with yyyy_mm_ddTHH:MM:SS+-Offset
But as far as i know I can just the regex to filter the time in this format. Dealing with the time is an essential part of the project and I want to make shure that I treat this part in a best practice way.
EDIT: In my code I to
for (Document doc : collection.find(query).projection(Projections.include(projectionList))) {
//Save the query result as a List of JSON-Objects
dataList.add(doc.toJson());
}
to save the results as a list of jsons. I know that the toJson method is deprecated but I wasn't able to find a way to convert the document into a JSON notation.
Is it possible to just get the key-value pair instead of the StartTime Object with the $numberLong key?
JsonWriterSettings settings = JsonWriterSettings.builder()
.int64Converter((value, writer) -> writer.writeNumber(value.toString())).build();
document.toJson(settings); // The output would contain simple long value
I know that the toJson method is deprecated
@medTech toJson method is not deprecated please refer the official documentation of Document here. Also, for json writer settings follow the link.