将多个用户输入值插入 Mongo 数据库集合时出现异常

Exception while inserting multiple user input values to Mongo db collection

我正在 JAVA-MongoDB 中编写基本的 CREATE 和 READ 操作。我正在尝试将用户输入的记录插入数据库并读取相同的内容。

这是我当前代码的样子-

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:PASSWD@CLUSTER.mongodb.net/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:PASSWD@CLUSTER.mongodb.net/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);


    }
}

我能够成功插入和读取一条记录。但是当我尝试在提示中输入一些不同的输入时,它会抛出以下异常 -

错误代码几乎说明了一切。

此数据库中已存在集合“students”

//Creating a collection
database.createCollection("students");

这是您代码中正确的部分,但必须运行只有一次,因为如果集合存在,将抛出异常...

所以只需删除它并记住,通过代码创建集合会在它们已经存在时抛出错误。

你知道你插入的列表是空的吗?

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);
}

将您的文档添加到列表中。

list.add(document);

增强的for循环用于遍历List。我不确定,但你已经想到了,但你可以查看 this 了解它。