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

时间:2016-04-15 17:40:13

标签: 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的原因。 AFAIK它不应该影响它。

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

  1. 获取用户的所有评论。
  2. 确保imgID与评论不同(因此只有已经评论过的imgs的id)
  3. 获取与这些ID相关的实际img对象。
  4. 将返回的imgs分开。
  5. 目前,第3步不起作用,我认为4也不会起作用,因为限制和跳过不会被应用于" uniqueImgs" 。 返回的是:

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

    我该如何解决这个问题?

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

1 个答案:

答案 0 :(得分:0)

当前版本(撰写本文时1.9.5)的{strong> 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);