如何存储到MongoDB数据库中并使用Java从同一MongoDB数据库读取/加载?
如何存储到MongoDB数据库中并使用Java从MongoDB数据库中读取
我写了这段代码,其中创建了数据库并存储了详细信息,但我似乎无法正确读取文件。它可以工作,但没有加载数据
private void saveandloadData(String[] trainSeats, String[] customerName, String[] traincustomerSeats, String userInput) {
MongoClient dbb = new MongoClient("localhost", 27017);
DB dbs = dbb.getDB("TrainCustomerandSeats");
DBCollection coll1 = dbs.getCollection("CW1");
DBCollection coll2 = dbs.getCollection("CW2");
DBCollection coll3 = dbs.getCollection("CW3");
if (userInput == "S" || userInput == "s"){
storeData(trainSeats, customerName, traincustomerSeats, coll1, coll2, coll3);
}else{
loadData(trainSeats, customerName, traincustomerSeats, coll1, coll2, coll3);
}
optionEnter(trainSeats, customerName, traincustomerSeats);
}
以下是我将数据存储到数据库中的部分:
private void storeData(String[] trainSeats, String[] customerName, String[] traincustomerSeats, DBCollection coll1, DBCollection coll2, DBCollection coll3) {
BasicDBObject oneDoc = new BasicDBObject();
for (int k = 1; k < trainSeats.length; k++){
oneDoc.append(String.valueOf(k), trainSeats[k]);
}
coll1.insert(oneDoc);
BasicDBObject twoDoc = new BasicDBObject();
for(int k = 1; k < customerName.length; k++){
twoDoc.append(String.valueOf(k), customerName[k]);
}
coll2.insert(twoDoc);
BasicDBObject threeDoc = new BasicDBObject();
for(int k = 1; k < traincustomerSeats.length; k++){
threeDoc.append(String.valueOf(k), traincustomerSeats[k]);
}
coll3.insert(threeDoc);
}
这里是我从db加载细节的地方,但由于某些原因它似乎不起作用:
private void loadData(String[] trainSeats, String[] customerName, String[] traincustomerSeats, DBCollection coll1, DBCollection coll2, DBCollection coll3) {
Cursor cursor = coll1.find();
Cursor cursor2 = coll2.find();
Cursor cursor3 = coll3.find();
while(cursor.hasNext()){
System.out.println(cursor.next());
}
while(cursor2.hasNext()){
System.out.println(cursor2.next());
}
while(cursor3.hasNext()){
System.out.println(cursor3.next());
}
}
这是运行时的输出-click to open output image
共 (0) 个答案