1

I'am trying to make some mongoDB query, but it doesn't work. This is how object look:

{
    "_id" : ObjectId("5c616e96aeddc93e2c076101"),
    "_class" : "school.domain.mongo.User",
    "username" : "test1234",
    "password" : "test1234",
    "status" : "ACTIVE",
    "time_created" : ISODate("2019-02-11T13:46:14.753+01:00"),
    "last_modified" : ISODate("2019-02-11T13:46:14.753+01:00")
}

Now i need to find user who are modified their data in the last 24 hours This is query that i try but it doesn't work

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

User must be active, last modified in range now and 24 hours in past And last modified must be different from time created, because if it's same than user is only created and not modified in the past 24 hours. I've tried this query and it still give me users that have same last_modified and time_created values.

3
  • Why unaccept the answer? Commented Feb 13, 2019 at 9:34
  • @AnthonyWinzlet accidentally. Could you pls look this second question if you know what could be problem Commented Feb 13, 2019 at 10:44
  • Sorry but I don't have idea about spring boot Commented Feb 13, 2019 at 10:47

2 Answers 2

1

You have to use $expr to match the two fields from the same document

db.getCollection('user').find({
  "status" : "ACTIVE",
  "last_modified": { "$lt": new Date(), "$gte": new Date(new Date().setDate(new Date().getDate()-1)) }
  "$expr": { "$ne": ["$last_modified", "$time_created"] }
})
Sign up to request clarification or add additional context in comments.

Comments

1

This query from @Anthony Winzlet working i Robo3T. But when i use it in spring to make custom query:

@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();

doesn't work, it return me some error on starting project. So 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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.