简体   繁体   English

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

[英]Get data from two collection using mongodb in spring boot

There are two collections in the below query(users and department).以下查询中有两个集合(用户和部门)。 I am able to get the data in mongo cell but when I tried with java code than got only one collection of data.我能够在 mongo 单元格中获取数据,但是当我尝试使用 java 代码时,只获得了一组数据。

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

Basically, I just want to convert to a java project. where using mongo template in spring-boot.

This is the service.这就是服务。 I always get users' data while requiring both collection data.我总是在需要收集数据的同时获取用户数据。

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();
   
}

} }

You can simply use你可以简单地使用

@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();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM