我开始使用monogDB在Java程序中保存和加载文件,但是在将数据库重新加载到我的程序时遇到了麻烦。当我通过Mongo Compass检查时,我的保存方法完全可以工作并创建了Mongo数据库,我的主要问题是我希望它将那些数据库值加载回我的数组中,该数组在运行代码时存储所有信息。
现在,当我关闭并打开Java代码并输入load方法时,它不会检索已保存的条目
private static void loadFile(String[] name) {
try (MongoClient mongoClient = (MongoClient) MongoClients.create(System.getProperty("mongodb.uri"))) {
MongoDatabase sampleTrainingDB = mongoClient.getDatabase("testDB");
MongoCollection<Document> gradesCollection = sampleTrainingDB.getCollection("collection");
// find one document with new Document
Document document = gradesCollection.find(new Document("title", "Customer")).first();
}
}
这些是存储在我的字符串数组中的值
[Jacky, Becky, Becky, vacant, Jacky, amy, vacant, vacant, amy, vacant, Jackie, vacant, vacant, Jackie, Jackie, Annie, vacant, vacant, Annie, vacant, Maria, vacant, vacant, Maria, vacant, vacant, Maria, vacant, vacant, vacant, vacant, vacant, vacant, vacant, vacant, vacant, vacant, vacant, vacant, vacant, vacant, vacant]
这是我的MongoDB的图片:View_Img
我只需要将它加载回我的数组中,这样我的程序就可以记住以前的条目。
*这是我保存文件的方式*
private static void saveFile(String[] name) {
// Creating a Mongo client
MongoClient mongo = new MongoClient("localhost", 27017);
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "trainDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
//Accessing the database
MongoDatabase database = mongo.getDatabase("testDB");
//Creating a collection
System.out.println("Collection created successfully");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("collection");
System.out.println("Collection myCollection selected successfully");
for (int i = 0; i < 42; i++) {
if (!name[i].equals("vacant") && (i == 0 || !name[i - 1].equals(name[i]))) {
Document document = new Document("title", "Customer")
.append("Name", name[i])
.append("Seats", i + 1);
collection.insertOne(document);
}
}
System.out.println("Document inserted successfully");
}
有谁可以帮助我吗 ?
最佳答案
我更新了您的loadFile
方法以获取名称数组。
private static void loadFile(String[] name) {
try (MongoClient mongoClient = MongoClients.create(System.getProperty("mongodb.uri"))) {
MongoDatabase sampleTrainingDB = mongoClient.getDatabase("testDB");
MongoCollection<Document> gradesCollection = sampleTrainingDB.getCollection("collection");
// find one document with new Document
Document document = gradesCollection.find(new Document("title", "Customer")).first();
/** Code added from here to the end of the method **/
/** Find all documents and get the names into an array **/
// First we will load the documents in to a List collection
List<Document> list = new ArrayList<>();
gradesCollection.find(new Document("title", "Customer"))
.into(list);
// From the list of we extract the name field and store in a string array
String [] names = list.stream()
.map(doc -> doc.get("name"))
.toArray(String[]::new);
System.out.println(Arrays.toString(names));
}
}
请注意,我还更改了
MongoClient
创建方法。