我使用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它不应该影响它。
理想情况下,我想要发生的是:
目前,第3步不起作用,我认为4也不会起作用,因为限制和跳过不会被应用于" uniqueImgs" 。 返回的是:
[{ "_id" : "570e2f5cb1b9125510a443f5" , "uniqueImgs" : [ ]}]
我该如何解决这个问题?
修改 存储的imgID不是ObjectID,而img集合中的_id是。这会有什么影响吗?
答案 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);