This question already has answers here:
Can I query MongoDB ObjectId by date?
(13 answers)
Closed 7 years ago.
How do you query time based queries from the ObjectID.timestamp()?
db.myCollectin.findOne()._id.getTimestamp()
I've tried
Date date = new Date();
BasicDBObject query = new BasicDBObject("timestamp", new BasicDBObject("$lt", date);
myCollection.findOne(query);
Problem:
Doesnt work
It doesn't work because your query looks for a field called timestamp which naturally doesn't exist.
You could do something like the shell query below, but be aware that Mongo will evaluate the JavaScript for every document in your collection - without using indices. I would recommend storing the date in a field on the documents if you need to query it regularly.
db.myCollection.find({$where: "this._id.getTimestamp() < ISODate('2015-03-04T21:18:21.419Z')"})
Related
This question already has answers here:
LocalDateTime and SQL Server JDBC 4.2 driver
(4 answers)
Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2
(1 answer)
Closed last year.
I was looking for a solution to my problem. I was coding my JdbcImpl file and I got an error when I was coding this :
rs.getDate create an error in a screen
Enchere enchereResultSet = new Enchere(
//Changer le getDate to LocalDateTime
rs.getDate("date_encheres"),
rs.getInt("montant_enchere"),
rs.getInt("no_article"),
rs.getInt("no_utilisateur"));
I found the fix! It seems simple, just go for this instead:
Enchere enchereResultSet = new Enchere(
//Changer le getDate to LocalDateTime
rs.getTimestamp("date_enchere").toLocalDateTime(),
rs.getInt("montant_enchere"),
rs.getInt("no_article"),
rs.getInt("no_utilisateur"));
The solution in a screen
Do I have the right to share the fix if I found it while writing a post here? I share it because it will maybe help beginner like me in the future.
This question already has answers here:
Use $strLenCP with Spring Data MongoDB
(3 answers)
Closed 2 years ago.
I have a mongoDB aggregate query using which i was able to get the length of the field which has max no of characters in the collection. I need help to convert that aggregate query to its equivalent in java.
Please find the aggregate query below:
db.getCollection('staff').aggregate([
{"$match": {"department": "technology"}},
{"$project": {"maxCharLength": {"$strLenCP": "$firstName"}}},
{"$sort": {"maxCharLength": -1}},{"$limit": 1}
])
I need to convert the above query to its equivalent in java. Please find the java code which im trying below: Im stuck with on how to use $strLenCP with project in java code below:
Aggregation agg = newAggregation(
match(Criteria.where("department").in("technology")),
project(""), //how to use $strLenCP here
sort(Sort.Direction.DESC, "maxCharLength"),
limit(1));
mongoTemplate.aggregate(agg, "staff", Staff.class);
Aggregation.project("firstName").andExpression("strLenCP(firstName)").as("length")
This question already has answers here:
Conversion from String to MongoDB ObjectID
(5 answers)
Closed 4 years ago.
e.g:
String hexString = "5afea3b5bc7f8d04fc61d525";
to an ObjectId like
ObjectId("5afea3b5bc7f8d04fc61d525")
Here the above string is obtained from objectId so while writing query in mongodb the _id of mongodb document doesnot match to the string.....Therefore how can i get the matched data from mongodb document by passing string as parameter from rest api to match that _id of mongodb document.
Use:
ObjectId objId = new ObjectId("5afea3b5bc7f8d04fc61d525");
See more ObjectId constructor here
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
This question already has answers here:
How to compare dates in hibernate
(8 answers)
Closed 8 years ago.
I have two tables to query, and so far I've come up with the following HQL-query:
From DriverEntity d
where exists (
From LicenceEntity l
where driverId = d.Id
and l.licenceType.id = '3'
and l.validFrom > TO_DATE('2014-01-01', 'YYYY-MM-DD')
and l.validFrom < TO_DATE('2014-04-17', 'YYYY-MM-DD')
and l.validTo > TO_DATE('2014-07-02', 'YYYY-MM-DD')
and l.validTo < TO_DATE('2095-07-12', 'YYYY-MM-DD')))
I'm querying two tables; one with licences and one with drivers. Each driver can have many licences.
The query works perfectly, but I would like to use Criteria instead to make it easier to edit when I add more search options.
What would this query look like using Criteria? I've looked into DetachedCriteria, but I don't understand it completely.
you can add a the subquery with help of DetachedCriteria:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Criteria criteria = Criteria.forClass(DriverEntity.class,"driver");
DetachedCriteria dc = DetachedCriteria.forClass(LicenceEntity.class,"licence");
dc.add(Property.forName("driver.id").eqProperty("licence.driverId"));
dc.add(Restrictions.between("validFrom", df.parse("2014-01-01"), df.parse("2014-04-17")));
dc.add(Restrictions.between("validTo", df.parse("2014-07-02"), df.parse("2095-07-12")));
criteria.add(Subqueries.exists(dc.setProjection(Projections.id())));
You can use Restrictions :
criteria.add(Restrictions.between("dateField", fromDate, toDate));
For your query :
criteria.add(Restrictions.between("validFrom", vFd1, vFd2));
criteria.add(Restrictions.between("validTo", vTd1, vTd2));
Where
vFd1,2 and vTd1,2 will be java calender dates with time set to zero.
Ref :
https://stackoverflow.com/a/10074111/3603806
according to Hibernate Developer Guide the developers should use CriteriaQuery instead of Criteria.
Look at this example thats explains how to create a multiple roots query or joins