【发布时间】:2018-01-31 16:22:47
【问题描述】:
我正在尝试使用 MongoDB 聚合转换以下数据。我想要对 array 'connections' 进行排序,并且我只想要名称与我的正则表达式匹配的数组元素。
在这种情况下,我希望array 按“步数”(中间朋友的数量)排序,并且只对那些名字中带有“汉”的人进行排序。在本例中,这将导致“Han Solo”。
sort 和 match2 操作都没有按照我的预期进行。数组没有排序,根本不匹配......我做错了什么?欢迎对此提供任何其他反馈,这是我第一次在Java 中使用MongoDB。
谢谢!
{
"name": "Luke Skywalker",
"_id": 1,
"connections": [
{
"name": "Tendra Risant",
"_id": 5,
"steps": 2
},
{
"name": "Han Solo",
"_id": 2,
"steps": 0
},
{
"name": "Leia Organa",
"_id": 3,
"steps": 0
},
{
"name": "Luke Skywalker",
"_id": 1,
"steps": 1
},
{
"name": "Lando Clarissian",
"_id": 4,
"steps": 1
}
]
}
public List<DBObject> search(final int id, final String value) {
AggregationOperation graphlookup = new AggregationOperation() {
@Override
public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) {
DBObject graphLookup = new BasicDBObject("from", "people")
.append("startWith", "$friends") //start at friends array
.append("connectFromField", "friends") //Links a value from the array friends to the ...
.append("connectToField", "_id") // ... id of a following document -> creating a chain of friends
.append("maxDepth",3)
.append("depthField","steps")
.append("as", "connections");
return new BasicDBObject("$graphLookup", graphLookup);
}
};
AggregationOperation project = new AggregationOperation() {
@Override
public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) {
DBObject match = new BasicDBObject("connections.name", 1)
.append("connections._id", 1)
.append("connections.steps", 1)
.append("name", 1);
return new BasicDBObject("$project", match);
}
};
AggregationOperation match = Aggregation.match(Criteria.where("_id").is(id));
AggregationOperation sort = Aggregation.sort(Sort.Direction.ASC, "connections.steps");
AggregationOperation match2 = Aggregation.match(Criteria.where("connections.name").regex(".*Han.*"));
Aggregation aggregation = Aggregation.newAggregation(graphlookup, project, sort, match, match2);
List<DBObject> output = mongoTemplate.aggregate(aggregation, "people", DBObject.class).getMappedResults();
return output;
}
【问题讨论】:
标签: java arrays mongodb sorting aggregate