0

How to use in springframework_data_mongodb like image?

enter image description here

prasad_
  • 12,755
  • 2
  • 24
  • 36
Wei
  • 13
  • 5
  • Please include the text (the query) from the image within the post. Also, see [how to ask](https://stackoverflow.com/help/how-to-ask). – prasad_ Sep 22 '20 at 10:24
  • See this post with similar question: [Create filter aggregation in spring](https://stackoverflow.com/questions/46767750/create-filter-aggregation-in-spring) – prasad_ Sep 22 '20 at 10:35

2 Answers2

0

This is an example from MongoDB manual for $filter aggregation converted to Spring Data MongoDB code. The same syntax can be applied to the question about using the $filter along with a condition.

MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "test");
Aggregation agg = newAggregation(
                      project()
                         .and(filter("items")
                              .as("item")
                              .by(Gte.valueOf("item.price").greaterThanEqualToValue(100)))
                         .as("items")
);
        
AggregationResults<Document> results = mongoOps.aggregate(agg, "sales", Document.class);        
results.forEach(doc -> System.out.println(doc.toJson()));

Reference: org.springframework.data.mongodb.core.aggregation.ArrayOperators.Filter.

prasad_
  • 12,755
  • 2
  • 24
  • 36
  • @Wei Please take a look at the example I had posted, and tell if it is useful. You can ask for any clarifications. – prasad_ Sep 22 '20 at 12:02
0

Here is the code specific to your problem if you use Java 8 and Spring Data MongoDB 3.0.3.RELEASE.

import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import static org.springframework.data.mongodb.core.aggregation.ArrayOperators.Filter.filter;
import static org.springframework.data.mongodb.core.query.Criteria.where;

MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "database");
ProjectionOperation projectionOperation =  project().and(filter("fields")
                 .as("field")
                 .by(Eq.valueOf("field.code").equalToValue("EngName")))
                 .as("fields");
MatchOperation matchOperation = match(where("fields.value").in("A","B"));
Aggregation agg = Aggregation.newAggregation(projectionOperation,matchOperation);
AggregationResults<Document> docs = mongoOps.aggregate(agg, "collection", Document.class);
        
docs.forEach(doc->System.out.println(doc));
RLD
  • 1,867
  • 3
  • 15
  • 20