Вопрос

I'm trying to simply do a comparison between my fields but it doesn't seems to work with spring data :

query.addCriteria(Criteria.where("active").gt("limit"));

Active and limit are 2 fields of my collection, and I wand to display all fields that exceed the limit. This limit is different for each item so I cannot do gt(200) for example...

There is anyway to do that ?

Это было полезно?

Решение

You can fall back to your java driver and issue a $where query:

 DBObject obj = new BasicDBObject();
 obj.put( "$where", "this.active > this.limit");
 ...

Anyway, you will have to issue a where command

Also, take into account the Warning paragraph

Другие советы

As you can see here, this kind of query is not supported in an efficient way by Mongo even if you are using the native shell. I think that is why it is not part of the Spring Data API (I couldn't find it anywhere in the docs and also have never used it myself), it would hide the computational complexity behind a statement that looks very simple, in particular to a developer used to relational databases.

Even if there is some sort of workaround for custom queries of which I'm not aware in Spring Data, I would not recommend it as it won't give you the same performance as you would expect from a RDBMS. The same goes for using the native Java driver as proposed in another answer to your question - it will work, but it might be slow.

You might want to consider a different way of storing your data if you want to use Mongo for your use case - note that it is not tailored to do what you want here. I don't know the context of your application, but if that's an option for you it would be preferable to store the result of this comparison in a boolean field. Of course that would not make much sense if you want to use many of those queries, in particular if you want to have the flexibility to use comparisons that were not considered when designing the schema.

Can be done much simpler

     class MyResult{
            long limit;
            long active;
            long  diff;

           //... getters and setters
     }
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.project("active", "limit").andExpression("active - limit").as("diff"),
                Aggregation.match(Criteria.where("diff").gt(0)),
                Aggregation.project("active", "limit","diff")
        );

        AggregationResults<MyResult> results = mongoOperations.aggregate(agg, "yourCollection", MyResult.class);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top