2
我正在使用Spring框架在我的MongoDB上执行聚合。然而,查找仍然失败,我不明白为什么。这里的查询:在Spring中使用查询进行聚合查询
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);
}
}
查找的春天MongoDB的版本无法识别这就是为什么我使用这个CustomAggregationOperation
。 AFAIK它不应该影响它。
理想的情况是我希望发生的是:
- 获取用户的所有评论。
- 确保imgID对于评论是不同的(所以只有已被评论的imgs的ID)
- 获取与这些ID相关的实际img对象。
- 分页返回的图片。
此刻,第3步不起作用,我认为4不会工作,因为limit和skip不会应用于“uniqueImgs”中的对象。 退货是什么:
[{ "_id" : "570e2f5cb1b9125510a443f5" , "uniqueImgs" : [ ]}]
我该如何解决这个问题?
编辑 存储的imgID不是ObjectID,而img集合中的_id是。会有什么影响?
如果这两个“类型”都没有,则同一'$ lookup'将不会成功,就像它使用不正确的BSON类型的任何查询也会失败一样。所以你需要将''imgID''数据改为'ObjectId'的值。 –
@NeilLunn谢谢,我认为它不工作的另一个原因是因为我刚刚看到我的mongo版本不支持$ lookup。 – Tometoyou
如果它不支持它,那么你会有一个大的“错误”,而不是一个空的数组。如果管道运算符不受支持,那么这就是抛出的错误。这些事情并不沉默。 –