I am writing a basic CREATE and READ operation in JAVA-MongoDB. I am trying to insert the records entered by user to the database and read the same.
This is how my current code looks-
Create.java-
import com.mongodb.Block;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.*;
import com.mongodb.client.model.InsertManyOptions;
import org.bson.Document;
import javax.print.Doc;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Create {
private static Scanner scanner = new Scanner(System.in);
private static String inputValue;
public static void main(String args[]) {
ConnectionString connectionString = new ConnectionString("mongodb srv://USER:[email protected]/mydb?retryWrites=true&w=majority");
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.build();
MongoClient mongoClient = MongoClients.create(settings);
MongoDatabase database = mongoClient.getDatabase("test");
System.out.println("Enter any string:");
inputValue = scanner.nextLine();
//Creating a collection
database.createCollection("students");
//Preparing a document
Document document = new Document("name", inputValue);
//Inserting the created documents
List<Document> list = new ArrayList<Document>();
for(Document d: list) {
list.add(d);
}
database.getCollection("students").insertMany(list, new InsertManyOptions().ordered(false));
System.out.println("Document inserted successfully");
mongoClient.close();
}
}
Read.java
import com.mongodb.Block;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.*;
import org.bson.Document;
import java.sql.SQLOutput;
import java.util.Iterator;
import java.util.Scanner;
public class Read {
private static Scanner scanner = new Scanner(System.in);
private static String inputValue;
public static void main(String args[]) {
ConnectionString connectionString = new ConnectionString("mongodb srv://USER:[email protected]/mydb?retryWrites=true&w=majority");
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.build();
MongoClient mongoClient = MongoClients.create(settings);
MongoDatabase database = mongoClient.getDatabase("test");
// Read Data from MongoDB
//Creating a collection object
MongoCollection<Document> collection = database.getCollection("students");
//Retrieving the documents
FindIterable<Document> iterDoc = collection.find();
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
mongoClient.close();
// findIterable.forEach(printBlock);
}
}
I am able to insert and read one record successfully. But when I try to enter some different input in the prompt it throws the below exception-
CodePudding user response:
The Error code pretty much says it all.
Collection "students" already exists in this DB
//Creating a collection
database.createCollection("students");
This is the part of your code that is correct, but must be run only once, because if the collection exists, an Exception will be thrown...
So just remove it and keep in mind that creation of Collections through code throws errors when they already exist.
And you do know that the list that you are inserting is empty right?
Document document = new Document("name", inputValue); // This is your created document
//Inserting the created documents
List<Document> list = new ArrayList<Document>(); // This is a list that CAN contain Documents but it is initialized and it is EMPTY
for(Document d: list) // The for loop will not be executed at all since the list is empty...
{
list.add(d);
}
Add your document to your list.
list.add(document);
The enhanced for
loop is used to traverse the List
. I am not sure but you had in mind but you can check this to learn about it.