I use Java spring and MongoDB repository in my project.
Here is DTO definition:
@Document(collection = "Info")
public class Info {
String id,
Integer count,
String type
…
}
I need to return from the query a list of IDs where the count field not zero and type filed has 'binary' text.
Here how I try to implement it:
@Query(value="{ 'count' : 0, 'type' : 'binary' }", fields="{ 'id' : 1 }")
List<String> getInfo();
I get this result from query above:
0={"_id": {"$oid": "5eb97a8139d4c62be4d90e4c"}}
1={"_id": {"$oid": "3ec97a8127d4c60cb4d90e9e"}}
And I expect this result:
{"5eb97a8139d4c62be4d90e4c", "3ec97a8127d4c60cb4d90e9e"}
So as you can see I expect to get a list of id strings from the query above.
Any idea what should I change in the query above to get the expected list of ids results?
No, that's impossible what you are thinking.
Reason : MongoDB can only return JSON Document. You can include the fields that you want to be there.
This suggestion that you can follow :
DTO Definition :
@Document(collection = "Info")
public class Info {
@Id
private String id;
private Integer count;
private String type;
// other fields and getters and setters
}
Sample Repository :
public interface InfoRepository extends MongoRepository<Info, String> {
@Query(value="{ 'count' : 0, 'type' : 'binary' }", fields="{ 'id' : 1 }")
List<Info> getInfo();
}
Sample Service class :
@Service
public class InfoService {
@Autowired
private InfoRepository infoRepository;
public List<String> getIds() {
return infoRepository.getInfo()
.stream()
.map(Info::getId)
.collect(Collectors.toList());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With