java - 在 Spring 中使用查找进行聚合查询

标签 java spring mongodb aggregation-framework spring-data-mongodb

我正在使用 Spring 框架对我的 mongodb 执行聚合。但是,查找一直失败,我不明白为什么。这是查询:

Aggregation aggregation = newAggregation(
    match(Criteria.where("idOfUser").is(loggedInAccount.getId())),
    group("imgID"),
    new CustomAggregationOperation(
        new BasicDBObject("$lookup",
        new BasicDBObject("from","img")
            .append("localField","_id")
            .append("foreignField","_id")
            .append("as","uniqueImgs")
        )
    ),
    limit(pageable.getPageSize()),
    skip(pageable.getPageSize()*pageable.getPageNumber())
);

AggregationResults aggregationResults = mongo.aggregate(aggregation, "comment", String.class); //Using String at the moment just to see the output clearly.

CustomAggregationOperation如下:

public class CustomAggregationOperation implements AggregationOperation {
    private DBObject operation;

    public CustomAggregationOperation (DBObject operation) {
        this.operation = operation;
    }

    @Override
    public DBObject toDBObject(AggregationOperationContext context) {
        return context.getMappedObject(operation);
    }
}

无法识别 Spring MongoDB 版本的查找,这就是我使用此 CustomAggregationOperation 的原因。据我所知,它不应该影响它。

理想情况下我想要发生的是:

  1. 获取用户的所有评论。
  2. 确保评论的 imgID 是不同的(因此只有被评论的 img 的 ID)
  3. 获取与这些 id 相关的实际 img 对象。
  4. 对返回的 img 进行分页。

目前,第 3 步不起作用,我认为第 4 步也不起作用,因为限制和跳过不会应用于“uniqueImgs”中的对象。 返回的是:

[{ "_id" : "570e2f5cb1b9125510a443f5" , "uniqueImgs" : [ ]}]

我该如何解决这个问题?

编辑 存储的 imgID 不是 ObjectID,而 img 集合中的 _id 是。会有什么影响吗?

最佳答案

当前版本(在撰写本文时 1.9.5 )有 support对于 $lookup 运算符,可以是 implemented作为(未经测试):

LookupOperation lookupOperation = LookupOperation.newLookup()
    .from("img")
    .localField("_id")
    .foreignField("_id")
    .as("uniqueImgs");

Aggregation agg = newAggregation(
    match(Criteria.where("idOfUser").is(loggedInAccount.getId())),
    group("imgID"),
    lookupOperation,
    limit(pageable.getPageSize()),
    skip(pageable.getPageSize()*pageable.getPageNumber())
);

AggregationResults aggregationResults = mongo.aggregate(agg, "comment", String.clas);

关于java - 在 Spring 中使用查找进行聚合查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36653595/

相关文章:

java - .jsp 文件中的 ModelAttribute : Can not resolve symbol. Spring

Java自定义Annotation聚合多个注解

java - 根据条件切换自动连线服务?

自 2.4 升级到 2.6 以来,MongoDB 索引查询返回不正确的值

mongodb - Robo 3T Sasl失败

java - 从 JSP 输入到 JavaFX

JavaFX - ListView 不填充 fxml 中的数据

mongodb - Mongo查找不包含给定值的文档(使用$not)

java - 在Java中使用reverse()命令?

java - 在Tomcat中创建mssql数据库jndi资源时出现异常