【问题标题】:Is there a way to access a value of a JSON document from mongodb which is inside an ArrayList?有没有办法从 ArrayList 中的 mongodb 访问 JSON 文档的值?
【发布时间】:2021-04-04 10:40:33
【问题描述】:

我有一个看起来像这样的代码 sn-p

MongoDatabase db = DbConnection.getDbConnection(); // connection is successfully made
MongoCollection collection = db.getCollection("candidates"); collection called candidates in the database

ArrayList<String> newList = new ArrayList<>();

FindIterable<Document> findIterable =  collection.find()
    .projection(fields(include("CandidateId"), excludeId()));

for(Document document:findIterable) {
  newList.add(String.valueOf(document));            
  }
System.out.println(newList);

输出如下所示

[Document{{CandidateId=1}}, Document{{CandidateId=2}}]

有什么办法可以得到一个像这样的arrayList,我只需要CandidateId字段的值

[1,2]

【问题讨论】:

    标签: java json mongodb arraylist


    【解决方案1】:

    你可以像这样使用Document::getString

    newList.add(document.getString("CandidateId"));            
    

    【讨论】:

      猜你喜欢
      • 2014-09-03
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 2023-03-07
      • 1970-01-01
      • 2019-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多