0

Is it possible to use insertMany for an ArrayList? I implemented a code but the data didn't insert into the collection.

ObjectId logId = new ObjectId();
    LogFile data =logfileRepo.save(new LogFile(String.valueOf(logId), fileName, now));
   
    ArrayList<Object> listdata = new ArrayList<>();
    if (arr != null) {

        //Iterating JSON array
        for (int i=0;i<arr.size();i++){

            //Adding each element of JSON array into ArrayList
            listdata.add(arr.get(i));
        }
    }
    MongoClient mongo = new MongoClient(new 
    MongoClientURI("mongodb+srv://rusiru:[email protected]/myFirstDatabase?retryWrites=true&w=majority"));
    MongoDatabase database = mongo.getDatabase("LApp");
    database.createCollection(String.valueOf(logId));
    database.getCollection(String.valueOf(logId)).insertMany(listdata)

here arris a jsonArray.

1 Answer 1

1

You will need to map those objects to MongoDB Documents.

void insertMany(java.util.List<? extends TDocument> documents)

Use a library that will do the mapping for you, like Morphia, or you can do like this:

ObjectId logId = new ObjectId();
LogFile data =logfileRepo.save(new LogFile(String.valueOf(logId), fileName, now));
List<Document> documents = arr.stream()
            .map(jsonStr -> Document.parse(jsonStr))
            .collect(Collectors.toList());

MongoClient mongo = new MongoClient(new 
MongoClientURI("mongodb+srv://rusiru:[email protected]/myFirstDatabase?retryWrites=true&w=majority"));
MongoDatabase database = mongo.getDatabase("LApp");
database.createCollection(String.valueOf(logId));
database.getCollection(String.valueOf(logId)).insertMany(documents);
Sign up to request clarification or add additional context in comments.

9 Comments

I didn't get the point can you bit explain, please
Sure. The method you are calling is expecting a certain Object type as argument - List of MongoDB Document. Does it compile for you with ArrayList<Object>?
Right, so you can call the method with ArrayList<Document>. If you already have a JSON, you can create a Document like this: Document.parse(jsonStr);
@Riyana I have edited my answer, so it will be more straightforward, let me know if it doesn't help
Fixed it. Is it OK now?
|

Your Answer

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