1

I'm trying to insert a single ArrayList containing JSONS into a mongodb collection with this,

MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("structure");
DBCollection collection = db.getCollection("chapter");
List<Document> data = new ArrayList<>();
collection.insertMany(data);
String str = "[{\"id\":1,\"data\":\"data1\"},{\"id\":2,\"data\":\"data2\"}]";
DBObject dbObject = (DBObject) JSON.parse(str);
collection.insert(dbObject);

But I get the exception,

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

Can anyone show me the correct way to do this?

Insert ArrayList mongodb The question above is about bulk insert of JSONS, not as a single one. My question is unique

2
  • Possible duplicate of Insert ArrayList mongodb Commented May 1, 2019 at 7:17
  • @MortezaJalambadani The question above is about bulk insert of JSONS, not as a single one. My question is unique Commented May 1, 2019 at 7:37

2 Answers 2

2

The exception gives a hint of what the problem is: a list cannot be used as a record (or a map-like data structure).

To quote the MongoDB documentation on documents that compose a collection:

Document Structure

MongoDB documents are composed of field-and-value pairs and have the following structure:

{
   field1: value1,
   field2: value2,
   field3: value3,
   ...
   fieldN: valueN
}

So what you need to do, in your case, because you just want to insert many documents in one call, is to use collection.insertMany:

List<Document> documents = ...; //convert your list to a List<Document>
collection.insertMany(documents);
Sign up to request clarification or add additional context in comments.

13 Comments

The method insertMany(List<DBObject>) is undefined for the type DBCollection
@G.Brown I have List<Document> as the type for documents. Can you please correct what you tried?
Yes, I tried. It seems the method of insertMany is absent.
It throws error like 'The method insertMany(List<Document>) is undefined for the type DBCollection'
No. The method is surely there on collection. Please share the code you have tried.
|
1

Have a look at this

https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/

List<DBobject> data = new ArrayList<>();
Colletions.insertMany(data);

1 Comment

The method insertMany(List<DBObject>) is undefined for the type DBCollection

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.