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
如果它不支持它,那麼你會有一個大的「錯誤」,而不是一個空的數組。如果管道運算符不受支持,那麼這就是拋出的錯誤。這些事情並不沉默。 –