繁体   English   中英

将JSON数组插入mongodb

[英]Insert JSON Array into mongodb

我正在尝试将表示JSON数组的字符串插入到mongodb集合中,

String str = "[{\"id\":1,\"data\":\"data1\"},{\"id\":2,\"data\":\"data2\"},{\"id\":3,\"data\":\"data3\"}]";
DBObject dbObject = (DBObject) JSON.parse(str);
collection.insert(dbObject);

但我得到例外,

Exception in thread "main" java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]

有谁能告诉我这样做的正确方法?

String json = "[{\"id\":1,\"data\":\"data1\"},{\"id\":2,\"data\":\"data2\"},{\"id\":3,\"data\":\"data3\"}]";
    MongoCredential credential = MongoCredential.createCredential("root", "sample", "root".toCharArray());
    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost"), Arrays.asList(credential));
    MongoDatabase db = mongoClient.getDatabase("sample");
    MongoCollection<Document> collection = db.getCollection("loginTracking");
    List<Document> jsonList = new ArrayList<Document>();
    net.sf.json.JSONArray array = net.sf.json.JSONArray.fromObject(json);
    for (Object object : array) {
        net.sf.json.JSONObject jsonStr = (net.sf.json.JSONObject) JSONSerializer.toJSON(object);
        Document jsnObject = Document.parse(jsonStr.toString());
        jsonList.add(jsnObject);

    }
    collection.insertMany(jsonList);
    mongoClient.close();

根据java docinsert()可以接受单个DBObject或它们的数组或List

因此,为了保存,您需要将JSON数组转换为数组/ DBObject列表,或者保存每个数组的项目

我找到了实现这个目标的好方法:

(ArrayList<Document>) JSON.parse("[String json array]");

我有一个问题,因为我需要在这个文档中附加一个Json数组的属性:

Document objAddendumVersion = new Document();
objAddendumVersion.append("_id", new ObjectId());
objAddendumVersion.append("Array", My Array here!);

但问题是Document.parse()不适用于Arrays,所以我可以使用上面的行来解决它。 所以最终的代码是:

Document objAddendumVersion = new Document();
objAddendumVersion.append("_id", new ObjectId());
objAddendumVersion.append("Array", (ArrayList<Document>) JSON.parse("[String json array]"));

它完美无缺。 是的,我知道存在更好的方法,但目前我正在使用它。

我等待对有同样麻烦的人有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM