Main Tutorials

Due to limitations of the BasicDBObject, you can’t add a second ‘$and’

Problem

Using Spring data and Mongodb, below is a function to find data within a date range.


public List<RequestAudit> findByIpAndDate(String ip, Date startDate, Date endDate) {

	Query query = new Query(
		Criteria.where("ip").is(ip)
		.andOperator(Criteria.where("createdDate").gte(startDate))
		.andOperator(Criteria.where("createdDate").lt(endDate))
	);
				
	return mongoOperation.find(query, RequestAudit.class);

}

It hits following error message :


org.springframework.data.mongodb.InvalidMongoDbApiUsageException: 
	Due to limitations of the com.mongodb.BasicDBObject, you can't add a second '$and' 
	expression specified as '$and : [ { "createdDate" : { "$lt" : { "$date" : "2013-02-25T16:00:00.000Z"}}}]'. 
	Criteria already contains '$and : [ { "createdDate" : { "$gte" : { "$date" : "2013-02-24T16:00:00.000Z"}}}]'

Solution

Adding multiple “$and” operators on the same field “createdDate” will make Spring interprets it into a wrong mongodb query. To fix it, change the query to follow :


	Query query = new Query(
		Criteria.where("ip").is(ip)
		.andOperator(
			Criteria.where("createdDate").lt(endDate),
			Criteria.where("createdDate").gte(startDate)
		)
	);

For multiple criteria on the same field, uses a “comma” to combine them.

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Sykobee
7 years ago

Query query = new Query()
.addCriteria(where(“ip”).is(ip))
.addCriteria(where(“createdDate”).lt(endDate).gte(startDate)));

Nik
3 years ago

hi ,I need to get from db field which is null and which is “siam” for example; and I cannot use your example.do you know to fix that code?
query.addCriteria( Criteria.where(“breed”).is(searchByInfoDto.getBreed())
.andOperator( Criteria.where(“breed”).is(null))
);

Michal
4 years ago

I found this for ReactiveMongoRepository (works)

@Query(value =”{‘startSessionData’ : {‘$gte’ : ?0, ‘$lte’ : ?1}}”, count = true)
Mono countByDateRange(long start, long end);

Phani Raj
5 years ago

Good one

kumar
8 years ago

how to use second or condition in spring mongo, for example i have 2 values and need to search first value in 2 different fields, same like second value also in 2 different fields, how to get it..?

2 values are Mongo and Rockpuri

‘$or : [ { “FIRST_NAME” : { “$in” : [ “MONGO”]}} , { “LAST_NAME” : { “$in” : [ “MONGO”]}}]’

WITH

‘$or : [ { “ADDRESS” : { “$in” : [ “ROCKPURI”]}} , { “CONTACT” : { “$in” : [ “ROCKPURI”]}}]’

the above query how to get the result in one shot..?

gopikumar
5 years ago
Reply to  kumar

have you solved? could you confirm this