首页 > 解决方案 > 如何根据实体属性和子文档属性查询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();
} 

这是获得预期结果的写入方法吗,请告诉我

标签: mongodbjava-8aggregation-framework

解决方案


推荐阅读