且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring Mongo 聚合项目过滤器

更新时间:2023-11-18 16:37:40

问题帖子中发布的聚合查询工作正常.聚合 ArrayOperators.In 语法的 MongoDB Spring Data API 不清楚.我无法实现基于此聚合的解决方案(网上也没有相关答案).

The aggregation query posted in the question post works fine. The MongoDB Spring Data API for the aggregation ArrayOperators.In syntax is not clear. I couldn't implement a solution based on this aggregation (and no answers related to on the net).

但是,替代解决方案基于以下聚合查询 - 它工作正常.

But, the alternative solution is based on the following aggregation query - and it works fine.

db.collection.aggregate( [
  { $unwind: "$employees" },
  { $match: { "employees.eeId": { $in: ["EE_ID1", "EE_ID3"] } } },
  { $group: { _id: "$_id", name: { $first: "$name" }, employees: { $push: "$employees" } } }
] )

Java 代码:

List<String> empsToMatch = Arrays.asList("EE_ID1", "EE_ID3");

MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "test");
Aggregation agg = newAggregation(
    unwind("employees"),
    match(Criteria.where("employees.eeId").in(empsToMatch )),
    group("_id")
        .first("name").as("name")
        .push("employees").as("employees")
 );

AggregationResults<Document> results = mongoOps.aggregate(agg, "collection", Document.class);