我有一个spring mongoDB收集用户,数据如下:
[{
"_id": {
"$oid": "5fd81fb277b245717d34c25e"
},
"userName": "banana",
"email": "banana",
"userRole": {
"$ref": "roles",
"$id": {
"$oid": "5fdc248b1846a46d71a71374"
}
}
},{
"_id": {
"$oid": "5fd81fd777b245717d34c25f"
},
"userName": "banana",
"email": "banana",
"userRole": {
"$ref": "roles",
"$id": {
"$oid": "5fd6e784f03b1f5e76699ebb"
}
}
},{
"_id": {
"$oid": "5fdc24691846a46d71a71373"
},
"userName": "banana",
"email": "banana",
"userRole": {
"$ref": "roles",
"$id": {
"$oid": "5fd6e784f03b1f5e76699ebb"
}
}
},{
"_id": {
"$oid": "5fe19f2f136f696e0bf83167"
},
"userName": "banana",
"email": "banana",
"userRole": {
"$ref": "roles",
"$id": {
"$oid": "5fdc248b1846a46d71a71374"
}
}
}]
我尝试用Spring MongoDB 在上面应用聚合
GroupOperation groupOperation = Aggregation.group("userRole.$id")
.addToSet("email").as("email")
.addToSet("firstName").as("firstName");
Aggregation aggregation = Aggregation.newAggregation(groupOperation);
AggregationResults<Map> result = mongoOperations
.aggregate(aggregation, "user", Map.class);
return result.getMappedResults();
但它不起作用。我的问题是Spring MongoDB Aggregation支持DBref吗?
Spring data mongo确实支持聚合,您可以在这里阅读更多信息-https://www.baeldung.com/spring-data-mongodb-projections-aggregations
根据您提供的集合示例,我没有看到任何名为firstName的字段,您可能指的是userName 如果是,那么您可以直接将此管道添加到您的存储库方法中。像这样的 *注意-这里的Result是具有与返回文档等效的字段的类 然后db.collection.aggregate({
"$group": {
"_id": {
"userRole": "$userRole.$id"
},
"email": {
"$addToSet": "$email"
},
"username": {
"$addToSet": "$userName"
}
}
})
public interface UserRepository extends MongoRepository<User, String> {
@Aggregation(pipeline = {
"{ "$group": { "_id": { "userRole": "$userRole.$id" }, "email": { "$addToSet": "$email" }, "username": { "$addToSet": "$userName" } } }"
})
AggregationResults<Result> findAndGroup();
}
@Autowired
private UserRepository userRepository;
userRepository.findAndGroup().getMappedResults();