【问题标题】:Get data from two collection using mongodb in spring boot在spring boot中使用mongodb从两个集合中获取数据
【发布时间】:2021-12-11 11:56:15
【问题描述】:

以下查询中有两个集合(用户和部门)。我能够在 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();
   
  }
}

【问题讨论】:

  • 你能告诉我我做错了什么
  • 你能发布你的收藏并展示你的预期结果吗?

标签: mongodb spring-boot mongodb-query aggregation-framework mongotemplate


【解决方案1】:

你可以简单地使用

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 2019-01-13
    • 2023-03-27
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多