我正在使用 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
的原因。据我所知,它不应该影响它。
理想情况下我想要发生的是:
- 获取用户的所有评论。
- 确保评论的 imgID 是不同的(因此只有被评论的 img 的 ID)
- 获取与这些 id 相关的实际 img 对象。
- 对返回的 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/