Ниже мой ДОКУМЕНТ:
@Document(collection = "products")
@Data
@EqualsAndHashCode
public class Product {
@Id
private String id;
@Field("lang_content_list")
private List<ProductLangContent> contentList;
@Data
public static class ProductLangContent {
@Field("lang")
private String lang;
}
}
Я хочу получить только те contentList, где lang = 'en'. lang уникален во внутреннем списке.
Примечание. Я использую Mongotemplate.
Мой образец json:
{
"_id" : ObjectId("5d2040f9f7c5ac1e9d8ef712"),
"lang_content_list" : [
{
"lang" : "en"
},
{
"lang" : "np"
}
]
"_class" : "com.sn.application.model.Product"
}
Желаемый результат запроса:
{
"_id" : ObjectId("5d2040f9f7c5ac1e9d8ef712"),
"lang_content_list" : [
{
"lang" : "en"
}
]
}
Я попробовал пару запросов, но не повезло:
Aggregation aggregation = newAggregation(
project().and(filter("contentList")
.as("item")
.by(valueOf(
"item.lang")
.equalToValue(
"en")))
.as("contentList")
);
List<Product> results = mongoTemplate.aggregate(aggregation, Product.class, Product.class).getMappedResults();
вывод: contentList равен null.
Пытался:
Criteria elementMatchCriteria = Criteria.where("contentList").elemMatch(Criteria.where("lang").is("en"));
Он дает все элементы в contentList. Я не хочу этого. Мне нужен только один объект во внутреннем списке, где lan = 'en' .
Заранее огромное спасибо.
Пытался:
AggregationOperation match = Aggregation.match(Criteria.where("contentList.lang").is("en"));
AggregationOperation unwind = Aggregation.unwind("contentList");
AggregationOperation group = Aggregation.group("id")
.push("contentList").as("contentList");
List<AggregationOperation> operations = new ArrayList<>();
operations.add(match);
operations.add(unwind);
operations.add(match);
operations.add(group);
Aggregation aggregation = Aggregation.newAggregation(operations);
List<Product> results = mongoTemplate.aggregate(aggregation, Product.class, Product.class).getMappedResults();
System.out.println(results.get(0).getContentList() != null);
вывод: false. Объект внутреннего массива имеет значение null.