mongo使用聚合查询时对字符串infonameabcd转成ArrayDocument或者Document进行解析
你可以使用Document.parse()方法将字符串转换为Document对象,然后使用Document.get()方法获取其中的字段值。
对于字符串info:"[{"name":"abcd"}]",可以按照以下步骤进行解析:
import org.bson.Document;
import org.json.JSONArray;
String info = "[{\"name\":\"abcd\"}]";
// 将字符串转换为JSONArray对象
JSONArray jsonArray = new JSONArray(info);
// 创建一个空的List<Document>
List<Document> documents = new ArrayList<>();
// 遍历JSONArray,将每个元素转换为Document对象,并添加到List中
for (int i = 0; i < jsonArray.length(); i++) {
String jsonStr = jsonArray.getJSONObject(i).toString();
Document document = Document.parse(jsonStr);
documents.add(document);
}
// 将List<Document>转换为Array<Document>
Document[] documentArray = documents.toArray(new Document[0]);
现在,你可以使用documentArray或documents进行进一步的操作和处理
原文地址: https://www.cveoy.top/t/topic/imo3 著作权归作者所有。请勿转载和采集!