我在我的项目中使用 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 字符串列表。
知道我应该在上面的查询中更改什么以获得预期的 ids 结果列表吗?
最佳答案
不,你想的不可能。
原因: MongoDB 只能返回JSON Document。您可以包含您想要的字段。
您可以遵循的建议:
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());
}
}
关于java - 如何返回查询 Java Spring Mongo Repository 中特定字段的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66766935/