MongoDB3.2的Java驅動基本推翻了之前2.x版本的用法,其使用方法有了很大的不同。本文整理了Java如何在有auth和無auth認證下連接MongoDB3.2以及一些基本的增刪改查的操作。
Java連接有auth認證
MongoClient client = null;
ServerAddress serverAddress = new ServerAddress("localhost", 27017);
List<ServerAddress> seeds = new ArrayList<ServerAddress>();
seeds.add(serverAddress);
MongoCredential credentials=
MongoCredential.createScramSha1Credential("gleradmin", "admin","gleradmin".toCharArray());
List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
credentialsList.add(credentials);
client = new MongoClient(seeds, credentialsList);
MongoDatabase db = client.getDatabase("testcol");
MongoCollection<Document> collection = db.getCollection("userinfo");
Java連接無有auth認證
MongoClient mongoClient = new MongoClient("192.168.0.102", 20000);
MongoDatabase db = mongoClient.getDatabase("testcol");
MongoCollection<Document> collection = db.getCollection("userinfo");
插入操作
//批量插入多個文檔
List<Document> list = new ArrayList<Document>();
for (int i = 0; i < 100; i++) {
Document document = new Document();
document.put("username", "user" + (i + 1));
document.put("password", "123456");
document.put("name", "user" + (i + 1));
document.put("sex", "man");
list.add(document);
}
collection.insertMany(list);
查詢操作
//全表掃描
MongoCursor<Document> cursor = collection.find().iterator();
while(cursor.hasNext()){
//cursor.next();
System.out.println(cursor.next());
}
//模糊查詢,字段"username"包含"11"的文檔
Pattern pattern = Pattern.compile("^.*11.*$", Pattern.CASE_INSENSITIVE);
BasicDBObject query = new BasicDBObject();
query.put("username",pattern);
FindIterable<Document> findIterable = collection.find(query);
MongoCursor<Document> cursor = findIterable.iterator();
while (cursor.hasNext()) {
//cursor.next();
System.out.println(cursor.next());
}
修改操作
//將文檔的字段"username"爲"user1"修改爲"Tom"
collection.findOneAndReplace(new Document("username","user1"), new Document("username","Tom"));
刪除操作
//刪除所有文檔(刪除一個用deleteOne()方法)
collection.deleteMany(new Document());
//刪除"sex"字段問"man"的所以文檔
collection.deleteMany(Filters.all("sex", "man"));
更多MongoDB操作請參考官方文檔。