Spring data mongodb query by json string - java

My code need to support any query that being sent by the client . The client will be sending the query as a json . I have done this using java mongo driver low level api using following code , BasicDBObject queryObject = (BasicDBObject) JSON.parse(whereJson.toString());
As i am a newbie in spring data mongodb , i am unable to find a similar solution in either Query or Criteria classes . I have checked different tutorials and couldn't find any . Is it possible to do in spring data mongodb or should i use low level apis itself ?

You can create Query instances from a plain JSON String by using BasicQuery object. The following example demonstrates how you can construct a Query instance from a plain JSON String:
BasicQuery query = new BasicQuery("{ age : { $lt : 50 } }");
List<Person> result = mongoTemplate.find(query, Person.class);
Another way which uses the low-level API:
DBObject dbObject = (DBObject) JSON.parse(query);
DBCursor cursor = mongoTemplate.getCollection("person").find(dbObject);
You can then map the return objects back to your Person POJO using the MongoConverter read() method:
List<Person> returnList = new ArrayList<Person>();
while (cursor.hasNext()) {
DBObject obj = cursor.next();
Person person = mongoTemplate.getConverter().read(Person.class, obj);
returnList.add(person);
}

Related

No results for $in clause in mongodb with java

I am trying to fetch few records based on list of ids. I am getting the results if I run the query directly on robomongo. But, the same doesn't work at code level in java.
Sample record:
{
"_id":"142",
"projectId":"PR_811",
"projectName":"ProjectTest007",
"entityName":"id-1412516",
"processName":"MSATesting",
"startDate":{
"$date":{
"$numberLong":"1666051200000"
}
},
"endDate":{
"$date":{
"$numberLong":"1666224000000"
}
},
"isRegulated":"No",
"tagNameList":[
],
"projectRole":{
"1464":"1464"
},
"projectPhase":{
"634e611de8ba26418e93ac96":"634e611de8ba26418e93ac96"
},
"status":"Approved"
}
BasicDBObject query = new BasicDBObject();
query.put("_id", new BasicDBObject("$in", projectIds)); //ProjectIds has list of ids as strings
DBCollection dbCollection = database.getCollection("Projects");
DBCursor cursor = dbCollection.find(query);
Not sure if I am missing something w.r.t in clause here.
some queries of robomongo vs our technical code method are different. For writing queries and searching in MongoDB check for $lookup command. Also you can just send id to model function and query it like collection.find(_id:id){ //results }

How to get list data using Criteria Mongotemplate in Nested Object

I want to get lists of data Review where reviewer object has id = "mawar_merah2".
How to create a query using MongoTemplate in spring boot.
this is my query:
Query query = new Query();
query.addCriteria(Criteria.where("reviewer").elemMatch(Criteria.where("id").is("mawar_merah2")));
List<Review> timeLinesReview = getMongoTemplate().find(query, Review.class);
return timeLinesReview;
Just use reviewer.id in query
Change
query.addCriteria(Criteria.where("reviewer").elemMatch(Criteria.where("id").is("mawar_merah2")));
To
query.addCriteria(Criteria.where("reviewer.id").is("mawar_merah2")));

Spring + MongoDB - MongoTemplate + Criteria Query

I am using Spring Boot + MongoDB. I need to query database based on some criteria where my methods looks like below:
#Override
public List<MyCollection> findBuyByCriteria(Request request) {
Query search = new Query();
search.addCriteria(Criteria.where("ItmId").in(request.getItmIds()));
return mongoTemplate.find(search, MyCollection.class);
}
Problem that I am facing is:
At line
search.addCriteria(Criteria.where("ItmId").in(request.getItmIds()));
request.getItmIds has 1 million Ids due to which I am getting an exception
org.bson.BsonMaximumSizeExceededException: Document size of 46282052 is larger than maximum of 16793600
Can anyone help me with this one?
If you are using Spring Data JPA, you can do something like:
findBySomeField(String someField)
If you have a more complex query, you can actually use JPQL and write a custom query.
#Query(value = "SELECT o.* from SomeObject o WHERE :someField IS NULL OR o.someField = :somefield)
public findBySomeField(#Param("someField") String someField);

How to do this MongoDB query using java?

I have to write a simple MongoDB query using java but am not able to do it.
The mongo query looks like this:
db.yourCollection.find({"$where" : "this.startDate < this.endDate"})
I have to write the above query using the QueryBuilder class. But am not able to do it in MongoDB java driver.
BasicDBObject document = new BasicDBObject();
document.put("id", 1001);
document.put("intValue", 1200);
document.put("updateValue", 2100);
DBObject query = QueryBuilder.start("intValue").lessThan("updateValue").get();
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println("Result : -"+cursor.next());}
The above code does not return any results. But if changed to updateValue into 2100 it is giving result. My question here is lessThan takes object as input parameter. Then how can I pass document field as an input parameter?
Ideally your mongoDB query should be like this: -
db.yourCollection.find({"startDate": {$lt: endDate}})
which can be written in Java like this: -
BasicDBObject query = new BasicDBObject("startDate", new BasicDBObject("$lt", endDate);
DBCursor cursor = coll.find(query);
You can take a look at Official Tutorial
If you want to use QueryBuilder, you can do it like this: -
DBObject query = QueryBuilder.start("startDate").lessThan("endDate").get();
DBCursor cursor = coll.find(query);
QueryBuilder helps construct complex queries to retrieve data from a collection in mongo db.
You can use the QueryBuilder like this.
BasicDBObject document = new BasicDBObject();
QueryBuilder qb = new QueryBuilder();
qb.or(new QueryBuilder().put("starting_date").is(null).put("ending_date").is(null).get(),
new QueryBuilder().put("starting_date").lessThanEquals("ending_date").get());
document.putAll(qb.get());
DBCursor cursor = getDbCollection().find(document)
QueryBuilder qb = new QueryBuilder(), instantiates a new QueryBuilder.
The logic build by the QueryBuilder in the example above is; (starting date = null and ending date = null) or (starting date <=ending date)
document.putAll(qb.get()) adds the logic constructed to the DBObject.

Spring Data MongoDB Date Between

I use spring data mongodb.
I want the records between two dates. The following MongoDB Query works:
db.posts.find({startDate: {$gte: start, $lt: end}});
My attempted Spring data query object code translation does not work:
Query query = new Query();
query.addCriteria(Criteria.where("startDate").gte(startDate)
.and("startDate").lt(endDate));
What is the correct order of method calls to build the Mongo query I need?
Do not include the 'and("startDate")' part in your criteria.
Instead of :
query.addCriteria(Criteria.where("startDate").gte(startDate).and("startDate").lt(endDate));
You should use:
query.addCriteria(Criteria.where("startDate").gte(startDate).lt(endDate));
When you include the 'and("startDate")' part, Mongo see's it as two different entries on the same property.
You also can add query annotaion:
#Query("{'date' : { $gte: ?0, $lte: ?1 } }")
public List<AnyYourObj> getObjectByDate(Date from, Date to);
Or proper spring data method signature:
public List<AnyYourObj> findByDateBetween(Date from, Date to);
Both of these approaches give the same result.
You can read more here https://www.baeldung.com/queries-in-spring-data-mongodb
and here https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/
Reference here
Query query = new Query(
Criteria.where("ip").is(ip)
.andOperator(
Criteria.where("createdDate").lt(endDate),
Criteria.where("createdDate").gte(startDate)
)
);
I had to find dates between on field publishedDate and here is how I did it:
Criteria publishedDateCriteria = Criteria
.where("publishedDateObject").gte(psDate)
.lte(peDate);
Query query = new Query(publishedDateCriteria);
mongoTemplate.find(query,
MyDocumentObject.class));
I did like this
public interface PolicyRepository extends MongoRepository<Policy, String> {
#Query("{'lastDate':{$gt:?0,$lt:?1}}")
public List<Policy> findAllPolicies(Date today,Date somedate);
}
This works on version 2.7.2 of the Java driver
DBCollection coll = db.getCollection("posts");
BasicDBObject date = new BasicDBObject();
date.append("$gte", new Date(startDate));
date.append("$lte", new Date(endDate));
DBObject query = new BasicDBObject();
query.put("date", date);
DBCursor cursor = coll.find(query);
Also, for the record you have "startDate" for both the gte and the lte parameters.
It works, he is some sample code:
Criteria criteria = Criteria.where("pt").gte(startDate)
.andOperator(Criteria.where("pt").lt(endDate));
public interface MyRepository extends MongoRepository<MyObject, MyObjectId> {
List<MyObject> findByMydatefieldBetween(DateTime startDate, DateTime endDate);
}
https://docs.spring.io/spring-data/mongodb/docs/2.2.x-SNAPSHOT/reference/html/#mongodb.repositories.queries
if (metaData.getToValue() == null){
dynamicCriteria = Criteria.where("metaData.key").is(metaData.getKey()).andOperator(Criteria.where("metaData.value").is(metaData.getFromValue()));
}else {
dynamicCriteria = Criteria.where("metaData.key").is(metaData.getKey()).orOperator(Criteria.where("metaData.value").gte(metaData.getFromValue()).lt(metaData.getToValue()));
}
Use MongoRepository Query method like this:
List<T> findByStartDateBetween(Range<Integer> dataRange);
use Range for detail range settings.
simliar question
Can you try this below query. This should work for your case.
Query query = new Query(
Criteria.andOperator(
Criteria.where("startDate").gte(startDate),
Criteria.where("startDate").lt(endDate)
)
);
Search By Date Column in spring boot mongo db using criteria(Complex Query)[Search by date column in spring boot mongodb using criteria][1]

Categories