我正在寻找一种在Resful Web API中使用Java实现graphlookup的方法。我正在尝试像在MongoDB(https://docs.mongodb.com/v3.4/reference/operator/aggregation/graphLookup/)上那样实现层次结构
{ "_id" : 1, "name" : "Dev" }
{ "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" }
{ "_id" : 3, "name" : "Ron", "reportsTo" : "Eliot" }
{ "_id" : 4, "name" : "Andrew", "reportsTo" : "Eliot" }
{ "_id" : 5, "name" : "Asya", "reportsTo" : "Ron" }
{ "_id" : 6, "name" : "Dan", "reportsTo" : "Andrew" }
这是员工集合,我想要的是能够创建存储在MongoDB中的结构
{
"_id" : 1,
"name" : "Dev",
"reportingHierarchy" : [ ]
}
{
"_id" : 2,
"name" : "Eliot",
"reportsTo" : "Dev",
"reportingHierarchy" : [
{ "_id" : 1, "name" : "Dev" }
]
}
{
"_id" : 3,
"name" : "Ron",
"reportsTo" : "Eliot",
"reportingHierarchy" : [
{ "_id" : 1, "name" : "Dev" },
{ "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" }
]
}
我已经看到类似这样的示例进行聚合,但是在graphlookup上什么也没有
Aggregation agg = newAggregation(
match(Criteria.where("pageId").is("2210")),
unwind("postIds"),
group("_id").sum("1").as("sum")
//project("$sum").and("pageId").previousOperation()
);
有没有办法将graphlookup变成这样的格式?我可以使用GraphLookupOperation然后使用诸如获取地图结果之类的方法来代替使用match,展开,分组的方法。
最佳答案
AggregationOperation aggregationOperation = new AggregationOperation() {
@Override public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) {
DBObject graphLookup = new BasicDBObject(
"from", "individual").append(
"startWith", "$reportsTo").append(
"connectFromField", "reportsTo").append(
"connectToField", "firstName").append(
"maxDepth", 2).append(
"as", "reportingHierarchy");
return new BasicDBObject("$graphLookup", graphLookup);
由于我使用的是旧版本,我认为1.10.0 spring mongo,此代码允许变通方法。现在,我遇到了“ reportingHierarchy”问题,看起来不像我想要的那样。它没有给我起名字。只是reportsTo和reportingHierarchy,其中还包括我不想要的_class。