Java操作MongoDB3.2概述

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操作请参考官方文档。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章