1

I have status collection and I have bellow Spring Data MongoDB query:

Query query = new Query(Criteria.where("reviewed").is(false)
            .and("active").is(true)
            .orOperator(
                Criteria.where("status").is("pending"),
                Criteria.where("status").is("inprogress")
                    .and("time").lt(new Date())
            )
        );

Now existing documents inside status collection might not have active, status, time fields, in this case query will return 0 results. I want to make them optional. If they are present they will be part of executing query otherwise they must be ignored.

After some research, I have come up with the below query:

Query query = new Query(Criteria.where("reviewed").is(false)
            .and("active").in(true, null)
            .orOperator(
                Criteria.where("status").in("pending", null),
                Criteria.where("status").in("inprogress", null)
                    .and("time").lt(new Date())
            )
        );

Is this the correct approach to achieve what I want or any suggestions please?

Nitesh Virani
  • 1,688
  • 4
  • 25
  • 41
  • 1
    Is it working? There is a difference between `null` and "not present", meaning where the field is not there at all. So depends on what your data actually looks like. – Blakes Seven Aug 05 '15 at 09:30
  • @Blakes I have not tested it as I am on different machine but I will update here soon. I have got the reference from this post http://stackoverflow.com/a/5315637/1371499 for the `null` – Nitesh Virani Aug 05 '15 at 09:41
  • 1
    @BlakesSeven, it is working. null will check the "not present" field as well, thanks – Nitesh Virani Aug 05 '15 at 18:51

0 Answers0