mongodb - 如何根据实体属性和子文档属性查询mongoDB
问题描述
我正在尝试做一个需要做的 mongoDB 操作
@Repository
public interface CustomRepository extends MongoRepository <MyEntity, String> {
List<MyEntity> findByAddressZipCode(@Param("effDate") LocalDate effDate,@Param("complete) complete);
}
@Document
public class MyEntity {
@Id
private String id;
private String firstName;
private String lastName;
private List<NestedEntity> nestedEntity;
private List<String> upcList;
}
public class NestedEntity{
private String prc;
private LocalDate effDate;
}
{
"firstName":"mathew",
"lastName":"Hill",
"nestedentity":[{
"prc":"12345",
"effDate":"2021-09-12"
},{
"prc":"12367",
"effDate":"2021-09-22"
},{
"prc":"12987",
"effDate":"2021-09-30"
}]
},
{
"firstName":"Paris",
"lastName":"Naf",
"nestedentity":[{
"prc":"4545",
"effDate":"2021-08-12"
},{
"prc":"125937",
"effDate":"2021-08-22"
},{
"prc":"12985",
"effDate":"2021-08-30"
}]
}
Expected Output
{
"firstName":"mathew",
"lastName":"Hill",
"nestedentity":[{
"prc":"12345",
"effDate":"2021-09-12"
},{
"prc":"12367",
"effDate":"2021-09-22"
},{
"prc":"12987",
"effDate":"2021-09-30"
}]
}
@Autowired
private MongoOperations mongoOperations;
...
public List<MyEntity> findByAddressZipCode(LocalDate effDate,String firstName) {
List<AggregationOperation> list = new ArrayList<AggregationOperation>();
list.add(Aggregation.unwind("nestedentity"));
list.add(Aggregation.match(Criteria.where("firstName").is(firstName)));
list.add(Aggregation.match(Criteria.where(".effDate").is(effDate.now())));
list.add(Aggregation.group("firstName").push("effDate").as("effDate"));
list.add(Aggregation.project("firstName", "lastName", "effDate"));
TypedAggregation<MyEntity> agg = Aggregation.newAggregation(MyEntity.class, list);
return mongoOperations.aggregate(agg, MyEntity.class,
MyEntity.class).getMappedResults();
}
这是获得预期结果的写入方法吗,请告诉我
解决方案
推荐阅读
- java - 将数组和其他内容传递给 var args
- amazon-web-services - AWS elasticbeanstalk 100 % of cpu is in use 降级
- python - 具有对数频率轴的 scipy 频谱图?
- javascript - 如何使用JS在固定宽度div的末尾自行检测一行上的“孤立”单词?
- json - 无法使用 POSTMAN 从站点获得响应
- reactjs - 访问除根以外的任何 URI 导致 404 - nginx
- c# - 将下一行中的新记录添加到 C# 中的现有 excel 文件中
- php - 将curl与http身份验证一起使用时如何修复需要身份验证的错误401
- reactjs - `height:'100%', width:'100%'`与`Flex:1`之间的区别
- google-chrome-extension - 在 Chrome/Firefox 扩展中加载 Javascript 之前将 HTML 插入页面