如何在查询JavaSpringMongo存储库中返回特定字段的列表?

mkh04yzy  于 2021-07-15  发布在  Java
关注(0)|答案(4)|浏览(432)

我在项目中使用JavaSpring和mongodb存储库。
定义如下:

  1. @Document(collection = "Info")
  2. public class Info {
  3. String id,
  4. Integer count,
  5. String type
  6. }

我需要从查询中返回一个id列表,其中count字段不是零,type字段有“binary”文本。
下面是我如何实现它:

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

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

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

我期待这个结果:

  1. {"5eb97a8139d4c62be4d90e4c", "3ec97a8127d4c60cb4d90e9e"}

如您所见,我希望从上面的查询中获得一个id字符串列表。
你知道我应该在上面的查询中修改什么才能得到预期的ids结果列表吗?

tnkciper

tnkciper1#

不,你想的不可能。
原因:mongodb只能返回json文档。你可以包括你想要的字段。
您可以遵循以下建议:
dto定义:

  1. @Document(collection = "Info")
  2. public class Info {
  3. @Id
  4. private String id;
  5. private Integer count;
  6. private String type;
  7. // other fields and getters and setters
  8. }

示例存储库:

  1. public interface InfoRepository extends MongoRepository<Info, String> {
  2. @Query(value="{ 'count' : 0, 'type' : 'binary' }", fields="{ 'id' : 1 }")
  3. List<Info> getInfo();
  4. }

服务类别示例:

  1. @Service
  2. public class InfoService {
  3. @Autowired
  4. private InfoRepository infoRepository;
  5. public List<String> getIds() {
  6. return infoRepository.getInfo()
  7. .stream()
  8. .map(Info::getId)
  9. .collect(Collectors.toList());
  10. }
  11. }
展开查看全部
6pp0gazn

6pp0gazn2#

他回来了 {"$oid": "5eb97a8139d4c62be4d90e4c"} 是objectid的mongodb扩展json表示。
它不返回字符串,因为数据库中存储的字段的类型为 ObjectID ,不是类型 String .
如果您希望它返回一个字符串,您应该使用聚合和$tostring操作符来转换它。

kzipqqlq

kzipqqlq3#

您能得到的最好结果是一个带有数组字段的文档,其中包含找到的ID,如下所示:

  1. {
  2. "ids" : [
  3. "606018909fb6351e4c34f964",
  4. "606018909fb6351e4c34f965"
  5. ]
  6. }

这可以通过如下聚合查询实现:

  1. db.Info.aggregate([
  2. {
  3. $match: {
  4. count: 0,
  5. type: "binary"
  6. }
  7. },
  8. {
  9. $project: { _id: { $toString: "$_id" } }
  10. },
  11. {
  12. $group: {
  13. _id: null,
  14. ids: { $push: "$_id" }
  15. }
  16. },
  17. {
  18. $project: { _id: 0 }
  19. }
  20. ])
展开查看全部
polkgigr

polkgigr4#

我有两个建议。
1.您可以使用jpa查询而不是命名查询

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

2.在业务逻辑中使用javastreamapi从上述结果中收集所有id作为列表。

  1. public class InfoServiceImpl {
  2. @Autowired
  3. private InfoRepository repository;
  4. public String getIds(final String type, final Integer count) {
  5. return repository.findByCountAndType(count, type)
  6. .stream()
  7. .map(Info::getId)
  8. .collect(Collectors.toList());
  9. }
展开查看全部

相关问题