Spring Data MongoDB 中的 Aggregate & Sort by Inner Array



我对mongoDB还很陌生。请耐心等待。

我有一个名为"用户"的集合,其中包含角色列表。一个用户可以有多个角色,因此角色列在一个数组中。我想按用户的角色名称对他们进行排序。

用户结构如下,

{
"_id": ObjectId("5bc910a39e53b62c7d4c4e62"),
"_class": "User",
"userName": "John",
"fullName": "Doe",
"roles": [
DBRef("roles",
ObjectId("5d5cf8ceb3773255b54d18c6")),
DBRef("roles",
ObjectId("5d5cf8ceb3773255b54d18c7"))
]
}

类别

@Document(collection = "users")
public class User {
@Id
private String id;
private String username;
private String fullName;
private boolean active;
@DBRef
private List<Role> roles;
//constructor, getter, setter
}

@Document(collection = "roles")
public class Role {
@Id
private String id;
private String name;
//constructor, getter, setter
}

,我试过以下几种

Criteria criteria = new Criteria();
setCriteriaReadOnlyIsNullOrReadOnlyIsFalse(criteria);
criteria.andOperator(Criteria.where("<condition>").is(<"condition_data">));
AggregationOperation userMatch = Aggregation.match(criteria);
LookupOperation lookupOperation = LookupOperation.newLookup()
.from("roles")
.localField("roles.id")
.foreignField("id")
.as("rolesAgg");
AggregationOperation sort = Aggregation.sort(Sort.Direction.DESC, "rolesAgg.name");
AggregationOperation project = Aggregation.project("id", "userName", "fullName","roles");

TypedAggregation<User> aggregation = newAggregation(User.class, userMatch, lookupOperation, sort, project);
return mongoOperations.aggregate(aggregation, User.class).getMappedResults();

这会产生结果,但无法排序,因为角色Agg是一个对象数组。这就是每个用户角色的显示方式。

"rolesAgg": [
{
"_id": ObjectId("5d5cf8ceb3773255b54d18c3"),
"name": "Super Admin"
},
{
"_id": ObjectId("5d5cf8ceb3773255b54d18c5"),
"name": "Customer Service"
},
{
"_id": ObjectId("5d5cf8ceb3773255b54d18c4"),
"name": "Admin"
}
]

有没有一种方法可以将角色agg.name提取到一个数组中,并使用它进行排序?我被卡住了。提前感谢你对我的帮助。

当对象在数组中时,不能进行排序。

[
{
"$unwind": "$rolesAgg"
},
{
"$sort": {
"rolesAgg.name": -1
}
},
{
$group: {
_id: "$_id",
username: {
"$first": "$username"
},
"fullname": {
"$first": "$fullname"
},
rolesAgg: {
$push: "$rolesAgg"
}
}
}
]

所以你需要做

平整阵列

Aggregation.unwind("$rolesAgg")

按名称排序

Aggregation.sort(Sort.Direction.DESC, "rolesAgg.name")

将所有背面分组

Aggregation.group("_id)
.first("username").as("username")
.first("fullname").as("fullname")
.push("rolesAgg").as("rolesAgg")

分别。

注意:如果你在分组时有更多的字段,也可以考虑

工作Mongo游乐场

最新更新