2

I have this MongoDb query:

db.getCollection('user').find({
    $and : [
        {"status" : "ACTIVE"},
        {"last_modified" : { $lt: new Date(), $gte: new Date(new Date().setDate(new Date().getDate()-1))}},
        {"$expr": { "$ne": ["$last_modified", "$time_created"] }}
    ]
})

It works in Robo3T, but when I put this in spring boot as custom query, it throws error on project start.

@Query("{ $and : [ {'status' : 'ACTIVE'}, {'last_modified' : { $lt: new Date(), $gte: new Date(new Date().setDate(new Date().getDate()-1))}}, {'$expr': { '$ne': ['$last_modified', '$time_created']}}]}")
    public List<User> findModifiedUsers();

I tried to make query with Criteria in spring:

Query query = new Query();
Criteria criteria = new Criteria();  
criteria.andOperator(Criteria.where("status").is(UserStatus.ACTIVE), Criteria.where("last_modified").lt(new Date()).gt(lastDay), Criteria.where("time_created").ne("last_modified"));

but it doesn't work, it returns me all users like there is no this last criteria not equal last_modified and time_created.

Does anyone know what could be problem?

1 Answer 1

1

I think that this feature is not supported yet by Criteria - check this https://jira.spring.io/browse/DATAMONGO-1845 . One workaround is to pass raw query via mongoTemplate like this:

BasicDBList expr = new BasicDBList();
expr.addAll(Arrays.asList("$last_modified","$time_created")); 

BasicDBList and = new BasicDBList();
and.add(new BasicDBObject("status","ACTIVE"));
and.add(new BasicDBObject("last_modified",new BasicDBObject("$lt",new Date()).append("$gte",lastDate)));
and.add(new BasicDBObject("$expr",new BasicDBObject("$ne",expr)));

Document document = new Document("$and",and); 
FindIterable<Document> result = mongoTemplate.getCollection("Users").find(document);
Sign up to request clarification or add additional context in comments.

2 Comments

I edited my answer, just create new variable with the expression

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.