Java實現對MongoDB的增刪改查
一、連接數據庫
連接數據庫,你需要指定數據庫名稱,如果指定的數據庫不存在,mongo會自動創建數據庫。
連接數據庫的Java代碼如下(無需密碼的連接):
public class MongTest {
public static void main(String[] args) {
try {
MongoClient mongoClient = new MongoClient("localhost",27017);//連接到 mongodb 服務
MongoDatabase mongoDatabase= mongoClient.getDatabase("mymong");//連接到數據庫
System.out.println("連接成功");
} catch (Exception e) {
System.err.println(e.getClass().getName()+":"+e.getMessage());
}
}
}
如果Mongo 需要驗證用戶名及密碼,可以使用以下代碼:
public class MongoDBJDBC {
public static void main(String[] args){
try {
//連接到MongoDB服務 如果是遠程連接可以替換“localhost”為服務器所在IP地址
//ServerAddress()兩個參數分別為服務器地址和端口
ServerAddress serverAddress = new ServerAddress("localhost",27017);
List addrs = new ArrayList();
addrs.add(serverAddress);
//MongoCredential.createScramSha1Credential()三個參數分別為用戶名數據庫名稱密碼
MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
Listcredentials = new ArrayList();
credentials.add(credential);
//通過連接認證獲取MongoDB連接
MongoClient mongoClient = new MongoClient(addrs,credentials);
//連接到數據庫
MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
System.out.println("Connect to database successfully");
} catch (Exception e) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
二、創建集合
使用 com.mongodb.client.MongoDatabase 類中的createCollection()來創建集合:
mongoDatabase.createCollection("test");//創建集合test
System.out.println("創建集合成功!");
三、獲取集合
使用com.mongodb.client.MongoDatabase類的getCollection() 方法來獲取一個集合 :
MongoCollection collection = mongoDatabase.getCollection("test");
System.out.println("集合選擇成功!");
四、插入文檔
使用com.mongodb.client.MongoCollection類的insertMany() 方法來插入一個文檔 :
Document document = new Document("title","UserInfo");
document.append("Name", "張三");
document.append("Age", 30);
document.append("Addr", "西安");
List documents = newArrayList();
documents.add(document);
collection.insertMany(documents);
System.out.println("文檔插入成功");
五、檢索所有文檔
使用 com.mongodb.client.MongoCollection 類中的find() 方法來獲取集合中的所有文檔。此方法返回一個遊標,所以需要遍歷這個遊標:
FindIterable findIterable= collection.find();
MongoCursor mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
將文檔信息封裝成對象:
List userList = newArrayList();
User user =null;
while(mongoCursor.hasNext()){
user = newUser();
user.setName(mongoCursor.next().getString("Name"));
user.setAge(mongoCursor.next().getInteger("Age"));
user.setAddr(mongoCursor.next().getString("Addr"))
userList.add(user);
}
for(User u:userList){
System.out.println(u);
}
User類的定義:
public classUser {
private String name;
private Integer age;
private String addr;
//省去set/get方法
@Override
public String toString() {
return "User [name="+ name+ ", age="+ age+ ", addr="+ addr+ "]";
}
}
六、更新文檔
使用 com.mongodb.client.MongoCollection 類中的updateMany() 方法來更新集合中的文檔。
//更新文檔 將文檔中Age=30的文檔修改為Age=50
collection.updateMany(Filters.eq("Age",30), new Document("$set",new Document("Age",50)));
//檢索查看結果
FindIterable<</span>Document> findIterable = collection.find();
MongoCursor<</span>Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
七、刪除第一個文檔
要刪除集合中的第一個文檔,首先需要使用com.mongodb.DBCollection類中的 findOne()方法來獲取第一個文檔,然後使用remove 方法刪除。
//刪除符合條件的第一個文檔
collection.deleteOne(Filters.eq("Age",30));
//刪除所有符合條件的文檔
collection.deleteMany (Filters.eq("Age",30));
Java實現對MongoDB的增刪改查