将JSON数组插入到MongoDB中

7
我正在尝试使用以下代码将代表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]

有人能向我展示正确的做法吗?

你的id在所有地方都一样,这正常吗?我不认为这是真正的原因,但这很奇怪。 - vincent
@vincent 我已经编辑了代码。尽管ID不同,但仍存在相同的错误。 - noob
1
你需要用一个数组保存单个文档,还是多个文档? - injecteer
1
在 MongoDB 控制台中添加字符串是有效的。这可能是 MongoDB-Java-Driver 中的一个 bug。 - Simulant
@injecteer 我想要保存多个文档。 - noob
3个回答

3
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();

虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - ᴄʀᴏᴢᴇᴛ

1
根据 java docinsert() 方法可以接受单个 DBObject 或其数组或 List
因此,为了保存数据,您需要将 JSON 数组转换为 DBObjects 数组/列表,或保存每个数组项。

0

我找到了一个很好的方法来实现这个:

(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()不能处理数组,所以我可以使用上面的代码来解决它。最终的代码如下:
Document objAddendumVersion = new Document();
objAddendumVersion.append("_id", new ObjectId());
objAddendumVersion.append("Array", (ArrayList<Document>) JSON.parse("[String json array]"));

它完美地运作。是的,我知道有更好的方法来做到这一点,但目前我正在使用这种方法。

我希望对于遇到相同问题的人有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接