如何在查询 Java Spring Mongo Repository 中返回特定字段的列表?

问题描述

我在我的项目中使用 Java spring 和 MongoDB 存储库。

这里是 DTO 定义:

@Document(collection = "Info")
public class Info  {

  String id,Integer count,String type
  …
}

我需要从查询中返回一个 ID 列表,其中计数字段不为零且类型字段具有“二进制”文本。

这里是我如何尝试实现它:

@Query(value="{ 'count' : 0,'type' : 'binary' }",fields="{ 'id' : 1 }")
List<String> getInfo();

我从上面的查询中得到了这个结果:

0={"_id": {"$oid": "5eb97a8139d4c62be4d90e4c"}}
1={"_id": {"$oid": "3ec97a8127d4c60cb4d90e9e"}}

我期待这个结果:

{"5eb97a8139d4c62be4d90e4c","3ec97a8127d4c60cb4d90e9e"}

如您所见,我希望从上面的查询中获得一个 id 字符串列表。

知道我应该在上面的查询中更改什么以获得预期的 id 结果列表吗?

解决方法

不,这不可能是你的想法。

原因: MongoDB 只能返回 JSON 文档。您可以包含您想要的字段。

您可以遵循的建议:

DTO 定义:

@Document(collection = "Info")
public class Info  {

  @Id
  private String id;
  
  private Integer count;
  
  private String type;
  
  // other fields and getters and setters
}

示例存储库:

public interface InfoRepository extends MongoRepository<Info,String> {

   @Query(value="{ 'count' : 0,'type' : 'binary' }",fields="{ 'id' : 1 }")
   List<Info> getInfo();
 
}

示例服务类:

@Service
public class InfoService {

   @Autowired 
   private InfoRepository infoRepository;

   public List<String> getIds() {
   
      return infoRepository.getInfo()
                      .stream()
                      .map(Info::getId)
                      .collect(Collectors.toList());    

   }

}

 
,

返回的 {"$oid": "5eb97a8139d4c62be4d90e4c"} 是 ObjectID 的 MongoDB Extended JSON 表示。

它没有返回字符串,因为存储在数据库中的字段是类型 ObjectID,而不是类型 String

如果你想让它返回一个字符串,你应该使用带有 $toString 运算符的聚合来转换它。

,

你能得到的最好的文档是一个包含数组字段的文档,其中的 id 如下所示:

{
    "ids" : [
        "606018909fb6351e4c34f964","606018909fb6351e4c34f965"
    ]
}

这可以通过像这样的聚合查询来实现:

db.Info.aggregate([
    {
        $match: {
            count: 0,type: "binary"
        }
    },{
        $project: { _id: { $toString: "$_id" } }
    },{
        $group: {
            _id: null,ids: { $push: "$_id" }
        }
    },{
        $project: { _id: 0 }
    }
])
,

我有 2 个建议。

1.您可以使用 JPA 查询代替命名查询

    public interface InfoRepository extends MongoRepository<Info,String> {
         List<Info> findByCountAndType(final Integer count,final String type);
    }

2.在您的业务逻辑中使用 java stream api 从上述结果中收集所有 id 作为 List。

    public class InfoServiceImpl {
       @Autowired
       private InfoRepository repository;

       public String getIds(final String type,final Integer count) {
           return repository.findByCountAndType(count,type)
                  .stream()
                  .map(Info::getId)
                  .collect(Collectors.toList());
       }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...