Query by date in mongodb using java - java

I was going to get distinct values form collection.
I stored time as follows:
"time" : ISODate("2017-01-26T09:46:26.523Z")
new ISO8601DateFormat() is not working, that gives me below error
org.bson.codecs.configuration.CodecConfigurationException: Can't find
a codec for class
com.fasterxml.jackson.databind.util.ISO8601DateFormat.
My code is looks like below.
Query query = new Query();
query.addCriteria(Criteria.where("user_id").is(id).and("time").gt(new ISO8601DateFormat()));
mongoTemplate.getCollection("user_log").distinct("timezone", query.getQueryObject())
My mongodb terminal command is follows and it works perfectly.
db.user_log.find({ "user_id" : "1" , "time" : { "$gt" : new ISODate("2017-01-25T00:16:15.184Z")}})
What is correct way to approach when I access from java?

Instant instant = Instant.parse("2017-01-25T00:16:15.184Z");
Date time = Date.from(instant);
Replace your time criteria with below
and("time").gt(time)

Related

java 9999-12-31 iso date inserted in mongo results as a non iso date inserted

I would like to insert the following document in mongodb:
Query query = new Query();
query.addCriteria(Criteria.where("client").is(client));
Update update = new Update();
update.set("dateTime", new DateTime());
update.set("maxDate", new DateTime("9999-12-31T00:00:00.000+01:00"));
mongoTemplate.upsert(query, update, MyClass.class);
and the inserted object is
{
"client" : "client",
"dateTime" : ISODate("2020-03-12T10:11:35.077Z"),
"maxDate" : Date(253402210800000)
}
I would like the maxDate to be in ISODate format. Is it possible ?
Is 9999-12-31T00:00:00.000+01:00 too far for mongodb?
Is there any issue with such a great value?
I read here https://docs.mongodb.com/manual/core/shell-types/ that mongoDB could support year 9999
EDIT with datagrip instead of robomongo usage
if I use datagrip to read the documents instead of robomongo, the format is correct. Could the issue come from robomongo display?
I haven’t tried or run this. But I believe using a different constructor for DateTime should resolve this.. please try below constructor for maxDate field..
public DateTime(int year,
int monthOfYear,
int dayOfMonth,
int hourOfDay,
int minuteOfHour,
int secondOfMinute,
int millisOfSecond,
DateTimeZone zone)

Could not save date field as ISO date in mongo db via Camel (Caused by: java.lang.IllegalArgumentException: Invalid BSON field name $date) [duplicate]

We are trying to insert a document with the current date as it's field. We are writing in java using eclipse plugin for mongodb. We want to execute the Date() command of mongo to get the date from mongo and not from java.
How can I execute this mongo query?
db.example.insert({"date":new Date()})
I found this question in a previews question but the answer was not helpful
Link
The standard driver takes java.util.date types and serializes as BSON dates. So with a collection object to "example"
Date now = new Date();
BasicDBObject timeNow = new BasicDBObject("date", now);
example.insert(timeNow);
If you are looking for a way to use the "server" time in operations, there is the $currentDate operator, but this works with "updates", so you would want an "upsert" operation:
BasicDBObject query = new BasicDBObect();
BasicDBObject update = new BasicDBObject("$currentDate",
new BasicDBObject("date", true)
);
example.update(query,update,true,false);
Since that actually is an update statement, you need to be careful that you are not actually matching any documents if you intend this to be an insert only. So it would be best to make sure your "query" contains unique information, such as a newly generated _id or something equally unique.
You can do it trying something like this:
db.example.insert({"date":ISODate("2016-03-03T08:00:00.000")});
Use this:
db.example.insert({"date":new Date(Date.now())});
There is a key difference I noted when using Date() as follows.
{ dateWhenCreated : Date() }
vs
{ dateWhenCreated : new Date() }
Notice the "new" keyword in the second usage. Whereas the first usage loads the data "as a string", the second one loads date as a field with date data type.
This might impact your sorting capability - dates stored as strings don't get sorted the same way as dates stored as dates.
Per the mongodb documentation here

Querying by date in mongo db

I am new to Mongodb. I want to find those objects stored in mongodb whose receivedOn date is greater than a particular date. My object structure is :
{
"_id" : ObjectId("591313fa79a7f2826cdfcdbd"),
"uuid" : "849cf178-bf19-4a32-bda8-b754551c57f0",
"status" : "SENT",
"receivedOn" : ISODate("2017-05-10T18:51:58.893+05:30"),
"scheduledOn" : ISODate("2017-05-10T18:51:58.893+05:30"),
"deliveredOn" : ISODate("2017-05-10T18:52:02.628+05:30")
}
I am using Jongo driver for querying. My query looks like:
collection.find("{\"receivedOn\": {$gte : #}}", javaDate);
I am getting no results from this query but there are documents in collection which should have been returned. What's wrong with my query?
db.CollectionName.find({"receivedOn" : new ISODate("2017-05-10T18:51:58.893+05:30") });
As you are using java,util.Date, there could be timezone issues when Date object is converted to json. Java might be adding/subtracting hours to your date based on timezone. Ideally while storing dates, they should be in UTC format, and while retrieving, they should be in UTC.

java mongodb search on a given date

We have a user_audit entity(table) in mongodb which stores all the login/logout information.
For example,
"_id" : ObjectId("5228cf0156961de6693b74c0"),
"active" : true,
"fname" : "Tom",
"lastlogin" : ISODate("2013-09-05T18:35:45.608Z"),
"lastloginip" : "0:0:0:0:0:0:0:1",
"lname" : "Bailey",
"lastlogout" : ISODate("2013-09-05T18:36:45.568Z"),
There are thousands of records in this table in production.
Now, the admin wants to look for all the logins on a particular date. i am not able to look for exact match of date because of the "time" information attached to ISODate in the "lastlogin" field. In Java, new Date() had been used to insert this field value.
The issue is the time information keeps changing for logins on a particular day.
Tried,
query.put("lastlogin", new BasicDBObject("$lte", givenDate).append("$gte", givenDate));
Obviously it does not return results because the time part of the date does not match.
The query passed from Java to mongo is:
query={ "lastlogin" : { "$lte" : { "$date" : "2013-09-05T04:00:00.000Z"} , "$gte" : {
"$date" : "2013-09-05T04:00:00.000Z"}}}
[Note: It defaults to 04:00:00.000Z always if we format with MM_dd_yyyy in java, not sure why..]
The issue is we have a lot of records in production database. For fresh records, i can blank out the time portion before inserting from Java. But for existing records, not sure how to handle it. How can i get the records on a given date?
According to mongodb cookbook, you are in the right direction. You may just query for something like
query.put("lastlogin", new BasicDBObject("$lt", givenDatePlusOneDay).append("$gte", givenDateAt00h00min));
which is an interval and not the same date.

Unexpected MongoDB "OR" query behaviour

I'm testing out spring-data and it's mongodb support.
I have a question about the query creation when using or-queries. Consider the following:
Query query = new Query().or(new Query(where("receiverId").is(userId)), new Query(where("requesterId").is(userId)));
query.and(where("status").is(status));
This will result in the following mongodb query:
"$or" : [ { "receiverId" : { "$oid" : "4d78696025d0d46b42d9c579"}} , { "requesterId" : { "$oid" : "4d78696025d0d46b42d9c579"}}] , "status" : "REQUESTED"}
This returns zero results while one is expected. Running this query in mongodb command results in following error:
error: { "$err" : "invalid operator: $oid", "code" : 10068 }
Modifying the query and running it in mongodb command works fine:
{ "$or" : [ { "receiverId" : ObjectId("4d78696025d0d46b42d9c579")} , { "requesterId" : ObjectId("4d78696025d0d46b42d9c579")}] , "status" : "REQUESTED"}
Notice the use of ObjectId("...") instead of $oid.
Am I going about something the wrong way? Maybe setting up the query wrong?
Are you inspecting that query variable at runtime or is that what you are seeing in MongoDB's logs?
Int he C# driver, if you inspect the query variable, you see $oid as well, but that is not the actual query that is sent to the server. At some point, it changes that to a valid MongoDB query.
If you are running on linux, you may want to start up mongosniff which will show you realtime queries, updates and inserts as they happen. If you are on Windows, you should start up mongod.exe with -vvvv flag which will enable it to log every query, update, insert, or command to the log file.
Then you can actually see the exact query that is being submitted.

Categories