[英]How to retrieve value of a specific field from a MongoDB collection in Java
I have a MongoDB database and I need to retrieve the list of values in a field.我有一个 MongoDB 数据库,我需要检索字段中的值列表。 I have tried with:
我试过:
FindIterable<Document> findIterable = collection.find(eq("data", data)).projection(and(Projections.include("servizio"), Projections.excludeId()));
ArrayList<Document> docs = new ArrayList();
findIterable.into(docs);
for (Document doc : docs) {
nomeServizioAltro += doc.toString();
}
but it prints但它打印
Document{{servizio=Antoniano}}Document{{servizio=Rapp}}Document{{servizio=Ree}}
While I want an array with these strings:虽然我想要一个包含这些字符串的数组:
Antoniano,Rapp,Ree
Is there a way to do it?有没有办法做到这一点?
You can try java 8 stream to output a list of servizio
values.您可以尝试使用 java 8 流来输出
servizio
值列表。
List<String> res = docs.stream().
map(doc-> doc.getString("servizio")).
collect(Collectors.toList());
Using for loop使用 for 循环
List<String> res = new ArrayList();
for(Document doc: docs) {
res.add(doc.getString("servizio"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.