在 Spring 中查找的聚合查询

Tom*_*you 5 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.
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

[{ "_id" : "570e2f5cb1b9125510a443f5" , "uniqueImgs" : [ ]}]
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

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

chr*_*dam 5

当前版本(在写作的时候1.9.5)已经支持$lookup运营商,并且可以实现为(未经测试):

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);
Run Code Online (Sandbox Code Playgroud)