How to project $strLenCP in Spring Data MongoDB [duplicate] - java

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")

Related

Spring data mongo GridFsOperation.findOne doesn't find first

I'm using Spring Data Mongo version 1.10.18 with Java 8. I don't understand the behavior I am seeing with the GridFsOperations.findOne method.
Query maxAccountSetVersionQuery = new Query().addCriteria(GridFsCriteria.whereMetaData("tenantId").is(tenantId))
.addCriteria(GridFsCriteria.whereMetaData("contextId").is(businessContextId))
.addCriteria(GridFsCriteria.whereMetaData("collection").is("genericAuthorizationAccount"))
.with(new Sort(Sort.Direction.DESC, "metadata.accountSetVersion"));
final GridFSDBFile findOneResult = gridOperations.findOne(maxAccountSetVersionQuery);
final List<GridFSDBFile> gridFSDBFiles = gridOperations.find(maxAccountSetVersionQuery);
final GridFSDBFile firstInListResult = gridFSDBFiles.get(0);
final String output = String.format("findOneResult: %s\nfirstInListResult: %s",
findOneResult.getMetaData().get("accountSetVersion"),
firstInListResult.getMetaData().get("accountSetVersion"));
System.out.println(output);
Console output is:
findOneResult: 1
firstInListResult: 4
To be clear here the answer I am expecting is 4 which means firstInListResult is referencing the expected document.
So, two questions:
Why aren't findOneResult and firstInListResult referencing one in the same document? Or to ask it another way, Why doesn't findOne find the first document?
Is there a way to get Spring Data Mongo to find the first document in the sorted query results instead of my code having to load the entire collection into memory just to get the first element?
It turns out that this is currently a bug in Spring Data MongoDb's GridFsTemplate implementation. https://jira.spring.io/browse/DATAMONGO-2411 Surprisingly a pull request with a fix was created just 4 days ago, after I originally asked this question.

Parse MongoDB query to Java [duplicate]

This question already has answers here:
MongoDB GUI client (cross-platform or Linux) [closed]
(5 answers)
Closed 3 years ago.
I need to perform the following MongoDB query in Java:
db.ventas.aggregate([
{
$sort: {"codArt._id": -1}
},
{
$group:{
_id: "$codArt._id",
denominacion: {"$first": "$codArt.denominacion"},
unidades: {"$sum": "$unidades"},
importe: {"$first": {"$multiply": [{"$sum": "$unidades"}, "$codArt.pvp"]}},
stock: {"$first": {"$subtract": ["$codArt.stock", "$unidades"]}}
}
}
])
Is there any library, which can do it?
Unfortunately, I can't install MongoDB Compass.
You could use something like Hibernate, but no automatic translation is provided... you'll need to build your model. It will be useful though if you do not want to build the inner query or need some portability.
http://hibernate.org/ogm/
There is a great tool to learn MongoDB Java Syntax and to work with MongoDB in general: Studio 3T, there you can generate a MongoDB query for the Java driver. Trial 30 days.
P.S. I'm not sure if this software requires admin rights to be installed.

How to get count after using find with Java MongoDB driver?

I was answered about constructing a MongoDb query
How to code collection find with regex and complex criteria using Java MongoDB driver?
Still the question about a count was unanswered:
So for this query how to write an analogous Java code returning count:
db.cache.find({objectKey: { $regex: 'Bos*'}, cacheVersionString:'08/03/15_11:05:09'}).count()
With MongoTemplate, it would be something like this:
Query query = new Query();
query.addCriteria(Criteria.where("objectKey").regex("Bos*"));
query.addCriteria(Criteria.where("cacheVersionString").is("08/03/15_11:05:09"));
long count = mongoTemplate.count(query, MyClass.class);

How do you execute java queries based on ObjectID.timestamp? [duplicate]

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')"})

How to access multiple tables in a single query using Hibernate Criteria? [duplicate]

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

Categories