Spring data mongodb search for ISO date - java

I am trying to search for date of birth using query
criteria = Criteria.where("dob").lte(new DateTime().toDate());
And spring data mongodb generate below query:
MongoTemplate: find using query:
{ "dob" : { "$lte" : { "$date" : "2015-05-16T07:55:23.257Z"}}}
fields: null for class: class com.temp.model.User in collection: user
But I did not get any result.
My dob field in mongodb:
{"dob" : ISODate("1991-01-23T00:00:00Z")}
How I can search for dob in ISODate format ?

This code should work fine for what you need:
criteria = Criteria.where("dob").lte(new java.util.Date());
My test is with following code, which does work fine:
Lis<User> users = mongoOps.find(query(where("isActive").is(true).and("CreatedDate").lte(new java.util.Date())), User.class);

Query would execute perfect from Spring data mongodb0
{ "dob" : { "$lte" : { "$date" : "2015-05-16T07:55:23.257Z"}}}.
But It will not execute from mongo CLI.
Query to execute on cli.
{dob:ISODate("2015-05-15T07:55:23.257Z")}
Thanks

For IDE use ISODate() for SPRING DAO convert string to Date object
query.addCriteria(Criteria.where("created").ne(null).andOperator(
Criteria.where("created").gte(DateUtils.getDate("2016-04-14 00:00:00", DateUtils.DB_FORMAT_DATETIME)),
Criteria.where("created").lte(DateUtils.getDate("2016-04-14 23:59:59", DateUtils.DB_FORMAT_DATETIME))
));
public final class DateUtils {
public static final String DB_FORMAT_DATETIME = "yyyy-M-d HH:mm:ss";
private DateUtils() {
// not publicly instantiable
}
public static Date getDate(String dateStr, String format) {
final DateFormat formatter = new SimpleDateFormat(format);
try {
return formatter.parse(dateStr);
} catch (ParseException e) {
return null;
}
}
}

val query = Query()
query.addCriteria(
Criteria("info.dob").gte(dob.atStartOfDay())

Related

Springboot MongoDB delete an object from array of objects

I'm trying to delete an object from an array of objects in mongodb collection. I've followed multiple answers from SO but I couldn't able to make it work.
customer_id and address_pin will be passed from querystring. I want to remove an object from address_india where address_pin matches with the value passed via querystring.
MongoDB collection object
{
"_id":{
"$oid":"61fa7de3b3de485b30403c56"
},
"customer_id":"c7e690cf-c8d9-4a7b-b146-ade742958452",
"customer_addresses":{
"address_india":[
{
"address_id":"ccc428bd-3e4d-49e5-8569-ebacb181ad1e",
"address_pin":"MD0BuCQUxT", // I've to remove this object
"address_type":"sales"
},
{
"address_id":"ccc428bd-3e4d-49e5-8569-ebacb181asdf",
"address_pin":"MD0BuCQUXy",
"address_type":"marketing"
}
]
},
"create_timestamp":{
"$numberLong":"1643806179346"
},
"modified_timestamp":{
"$numberLong":"1643806179346"
}
}
Controller
return new ResponseEntity<CustomerAddressResponse>(
this.customerAddressService.deleteCustomerAddressById(customerId),
HandleResponseHeader.getResponseHeaders(UUID), HttpStatus.OK);
ServiceImpl
#Override
public CustomerAddressResponse deleteCustomerAddressById(String customerId)
throws Exception {
try {
if (isValidUUID(customerId)) {
Date now = new Date();
Long dateStartTime = now.getTime();
Stopwatch stopWatch = Stopwatch.createStarted();
CustomerAddress customerAddress = customerAddressDao
.findByCustomerId(customerId);
String pin = httpServletRequest.getParameter("address_pin")
.trim();
Query query = new Query();
query.addCriteria(Criteria.where("customer_id")
.is(customerId)
.and("customer_addresses.address_india")
.elemMatch(Criteria.where("address_pin").is(pin)));
Update update = new Update();
update.pull("customer_addresses.address_india", new Query().addCriteria(Criteria.where("address_pin").is(pin)));
FindAndModifyOptions options = FindAndModifyOptions.options();
options.returnNew(true);
MongoTemplate template = null;
template.findAndModify(query, update, options, CustomerAddress.class);
}
}
}
I'm getting java.lang.NullPointerException at template.findAndModify(query, update, options, CustomerAddress.class);
How do I delete an object from array of objects in mongodb from springboot?
This is how you do from mongo js shell for single document , it may give you some idea on how to do from springboot:
db.collection.update(
{
"customer_id": "c7e690cf-c8d9-4a7b-b146-ade742958452"},
{
$pull: {
"customer_addresses.address_india": {
"address_pin": "MD0BuCQUxT"
}
}
})
playground

Inserting Java Object to MongoDB with date value inserted as String

I have the below mongoDB code with Java, I am trying to insert the TechnologyDetails to mongoDB,
and in the mapper method I am setting all the values and persisting to DB. The problem is as the collection.insertOne() takes only document as an argument, after I convert the TechnologyDetails pojo to Document, during insertion to MongoDB the "createdAt" Date datatype field is being inserted as String to DB. Could anyone help on this, how to maintain the same dataType even after converting the pojo to Document. So that I insert Date as Date to mongoDb. Thanks.
final FindIterable<Document> iterable = technologiesCollection
.find(and(eq(APPLICATION, techKey.getApplication()), eq(VERSION, techKey.getVersion()),
eq(TECHNOLOGY, techKey.getTechnology())));
final Document document = iterable.first();
final ObjectMapper mapper = new ObjectMapper();
final TechnologyDetails technology = mapper.convertValue(document, TechnologyDetails.class);
if (technology == null) {
//mapper method to set the technology fields
Document tech = mapper(techKey, hosts);
try {
technologiesCollection.insertOne(tech);
} catch (Exception e) {
LOGGER.error("error", e);
}
}
private Document mapper(final TechnologyKey techKey, final Set<ApplicationHost> hosts) {
final TechnologyDetails technology = new TechnologyDetails();
final TransactionDetail txnDetail = new TransactionDetail();
final UserDetail userDetail = new UserDetail();
technology.setApplication(techKey.getApplication());
technology.setVersion(techKey.getVersion());
technology.setTechnology(techKey.getTechnology());
if (hosts != null) {
technology.setApplicationHosts(hosts);
}
userDetail.setDsid("123");
userDetail.setName("APP");
txnDetail.setCreatedBy(userDetail);
final Date date = new Date(System.currentTimeMillis());
txnDetail.setCreatedAt(date);
technology.setTxnDetails(txnDetail);
Document document = Document.parse(new JSONObject(technology).toString());
return document;
}
I would recommend using an ODM
https://www.baeldung.com/mongodb-morphia

Unparsable Date despite perfect format

I'm trying to parse a date departureTime:
String departureTime2, departureTime;
departureTime2 = departureTime = "2018-01-01 11:11:11.1";
Using the JUnit when method
when(bookingController.booking( departureTime, departureTime2).thenAnswer(new Answer<MockHttpSession>()
{
#Override
public MockHttpSession answer(InvocationOnMock invocation) throws Throwable
{
Object[] args = invocation.getArguments();
return (MockHttpSession) args[0];
}
});
My booking method in BookingController
#RequestMapping(value = "/bookingsingle", method = RequestMethod.POST)
public String bookingSingle(#RequestParam String departureTime,..)'
formats the date using
Date departureTimeAsDate = null;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.S", Locale.ENGLISH);
try { departureTimeAsDate = df.parse(departureTime); } catch (ParseException e) { e.printStackTrace(); }
However I receive the error
java.text.ParseException: Unparseable date: "2018-01-01 11:11:11.1"
The date appears to be in the perfect format, and upon using the same code in a Java fiddle tool it compiles, however in intellij it runs into the error. Any suggestions would be appreciated.
EDIT:
I believe the problem may lie somewhere in the passing of the String in the when() method. Note that booking() has many irrelevant parameters I have excluded.

Setting a JCR Date property

I'm having some trouble writing properties of a cq:PageContent. releaseDate (type Date) is giving me some trouble. The following method is from a sling-junit test where I'm calling from a #Before method.
private void setNewsReleaseDate(Resource res, int month)
throws InvalidDateException {
String date = "2014-%sT11:31:00.000-04:00"; //07-23
Calendar rd = DateUtil.parseISO8601(String.format(date, "0"+month+"-23")); //iso8601Date
ModifiableValueMap modMap = res.adaptTo(ModifiableValueMap.class);
if (modMap != null) {
modMap.put("releaseDate", rd); // this is a Date property
/* also tried below, which also fails
modMap.put("releaseDate", String.format(date, "0"+month+"-23"));
*/
}
}
I get this error...
Value for key releaseDate can't be put into node:java.util.GregorianCalendar[time=1406129460000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT-04:00",offset=-14400000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=6,WEEK_OF_.... ]
I changed the method by passing in the page, and then get the /jcr:content below the page that I wanted to edit the properties of...
private void setNewsReleaseDate(Page page, int month) throws InvalidDateException{
LOGGER.info("change prop at page path "+page.getPath());
Resource res = rr.getResource(page.getPath()+"/jcr:content");
String date = "2014-%sT11:31:00.000-04:00"; //07-23
Calendar rd = DateUtil.parseISO8601(String.format(date, "0"+month+"-23")); //iso8601Date
ModifiableValueMap modMap = res.adaptTo(ModifiableValueMap.class);
if (modMap != null) {
modMap.put("releaseDate", rd); // this is a Date property
modMap.put("notes", "hello"); // a string property
}
}

Solrj Date request

How to request by date using SolrJ?
I get as a parameter a date in this format '01/10/2014'. Then I convert this format to a Date object and convert the object to a UTC format. Here is a code example of what I am doing :
public class DateHelper {
public static final String DD_MM_YYYY_FORMAT = "dd/MM/yyyy";
public static final String SOLR_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static Date getDateFromString(String date, String format) {
if (StringUtils.isNotEmpty(date)) {
try {
return FastDateFormat.getInstance(format).parse(date);
} catch (ParseException e) {
LOGGER.error(e.getMessage());
}
}
return null;
}
public static String getStringFromDate(Date date, String format) {
if (date != null) {
try {
return FastDateFormat.getInstance(format).format(date);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
return "";
}
public static void main(String...args){
Date dateFromString = DateHelper.getDateFromString('01/10/2014', DateHelper.DD_MM_YYYY_FORMAT);
String date = DateHelper.getStringFromDate(dateFromString, DateHelper.SOLR_DATE_FORMAT);
System.out.println(date);
}
}
This small program displays '2014-10-01T00:00:00Z'. When I try to submit this date in Solr using a filter query, I receive this error from Sorl :
org.apache.solr.client.solrj.impl.HttpSolrServer$RemoteSolrException: Invalid Date String:'2014-10-01T00'
Here is my Solr query :
SolrQuery solrQuery = new SolrQuery("*:*");
String date = String.format( "date:%s",dateInput);
query.addFilterQuery(date);
getSolrServer().query(solrQuery, METHOD.POST);
How can I solve this problem? THx for your help.
P.S : The class FastDateFormat is from Apache Commons Lang 3. I am using solr version 4.8.1.
This happens because of the way filterQuery is created:
String date = String.format( "date:%s",dateInput);
query.addFilterQuery(date);
That way the solr gets:
date:2014-10-01T00:00:00Z
And the exception is thrown because of the multiple : symbols that the Query Parser cannot parse correctly.
In order to fix it the special characters that are part of Query Syntax should be escaped.
From the java side it can be done this way (using ClientUtils.escapeQueryChars from SolrJ):
String date = String.format( "date:%s", ClientUtils.escapeQueryChars(dateInput));
query.addFilterQuery(date);
Syntax to query solr date field -- Date:[YYYY-MM-DDTHH:mm:ssZ]

Categories

Resources