標籤:直接 sof str uri and user rtm 避免 rto
1.串連
①方式一
MongoClientOptions.Builder builder = MongoClientOptions.builder(); //可以通過builder做各種詳細配置 MongoClientOptions myOptions = builder.build(); ArrayList<ServerAddress> serverAddressList = new ArrayList(); ServerAddress record = new ServerAddress("localhost", 27017); //IP、連接埠 serverAddressList.add(record); //使用者名稱、預設庫名、密碼 MongoCredential credential = MongoCredential.createCredential("testUser", "test", "testPwd".toCharArray()); MongoClient mongoClient = new MongoClient(serverAddressList, credential, myOptions);
②方式二
//使用者名稱、密碼、IP、連接埠、預設庫名 String sURI = String.format("mongodb://%s:%[email protected]%s:%d/%s", "testUser", "testPwd", "localhost", 27017, "test"); MongoClient mongoClient = new MongoClient(new MongoClientURI(sURI));
③方式三(沒開啟許可權驗證模式時可使用)
//不使用使用者名稱和密碼直接進行登陸(方便初學者,避免過於複雜的設定) MongoClient mongoClient = new MongoClient("localhost", 27017);
2.中間步驟(建立一個collection存放資料,相當於表table)
MongoDatabase dbTest = mongoClient.getDatabase("test"); //如果不存在,則增加collection MongoCollection<Document> collection = dbTest.getCollection("test_collection"); if (collection == null) { dbTest.createCollection("test_collection"); }
3.insert
//insert 增加資料 Document doc = new Document(); doc.append("Name", "name1"); doc.append("Age", 20); //collection.insertOne(doc); //增加一條資料 //增加多條資料 Document doc2 = new Document(); doc2.append("Name", "name2"); doc2.append("Age", 30); ArrayList dataList = new ArrayList(); dataList.add(doc); dataList.add(doc2); collection.insertMany(dataList);
4.delete
//delete 刪除資料 BasicDBObject delSql = new BasicDBObject("Name", "name1"); collection.findOneAndDelete(delSql); //刪除一條 //collection.deleteMany(delSql); //刪除多條
5.update
//update 修改資料 BasicDBObject updateOldSql = new BasicDBObject("Name", "name2"); //更新一條資料 BasicDBObject updateNewOneSql = new BasicDBObject("$set", new BasicDBObject("Name", "name1")); //collection.updateOne(updateOldSql,updateNewOneSql); //更新多條資料 BasicDBObject updateNewManySql = new BasicDBObject("$set", new BasicDBObject("Name", "name1").append("Age",66)); //修改多個欄位 collection.updateMany(updateOldSql, updateNewManySql);
6.query
//查詢資料 BasicDBObject querySql = new BasicDBObject("Name", "name1"); FindIterable<Document> queryRst = collection.find(querySql); //這裡可以做sort和filter等操作 MongoCursor<Document> cursor = queryRst.iterator(); while (cursor.hasNext()){ System.out.println(cursor.next());//輸出每一行資料 }
以上。
Java操作MongoDB:串連&增&刪&改&查