在spring boot中使用mongodb获取两个集合的数据



下面的查询中有两个集合(用户和部门)。我能够在Mongo shell中获得数据,但当我尝试使用Java代码时,我只得到一个数据集合。

db.users.aggregate([
{
"$lookup":{
"from":"department",
"localField":"user_department_id",
"foreignField":"department_id"
}
]);

基本上,我只是想转换成一个Java项目,并在Spring-Boot中使用Mongo模板。

这是服务。我总是得到用户的数据,同时要求收集数据。

public class UsersService {
@Autowired
private MongoTemplate mongoTemplate;
public void lookupOperation(){
LookupOperation lookupOperation = LookupOperation.newLookup()
.from("department")
.localField("user_department_id")
.foreignField("department_id")
.as("departments");
Aggregation aggregation = Aggregation.newAggregation(lookupOperation);
List<UsersDeptResult> results = mongoTemplate.aggregate(aggregation, "department", users.class).getMappedResults();

}
}

你可以直接使用

@Autowired
private MongoTemplate mongoTemplate;
public List<YOUR_CONVERTER_CLASS> test() {
Aggregation aggregation = Aggregation.newAggregation(   
lookup("department","user_department_id","department_id","departments")
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), YOUR_CONVERTER_CLASS.class).getMappedResults();
}

最新更新