Java操做MongoDB:鏈接&增&刪&改&查

1.鏈接mongodb

①方式一app

        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);

②方式二ui

        //用戶名、密碼、IP、端口、默認庫名
        String sURI = String.format("mongodb://%s:%s@%s:%d/%s", "testUser", "testPwd", "localhost", 27017, "test"); MongoClient mongoClient = new MongoClient(new MongoClientURI(sURI));

③方式三(沒開啓權限驗證模式時可以使用)spa

        //不使用用戶名和密碼直接進行登錄(方便初學者,避免過於複雜的設置)
        MongoClient mongoClient = new MongoClient("localhost", 27017);

 

2.中間步驟(建立一個collection存放數據,至關於表table)code

        MongoDatabase dbTest = mongoClient.getDatabase("test"); //若是不存在,則增長collection
        MongoCollection<Document> collection = dbTest.getCollection("test_collection"); if (collection == null) { dbTest.createCollection("test_collection"); }

 

3.insertorm

        //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.deleteserver

        //delete 刪除數據
        BasicDBObject delSql = new BasicDBObject("Name", "name1"); collection.findOneAndDelete(delSql); //刪除一條 //collection.deleteMany(delSql); //刪除多條

 

5.updateblog

        //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.queryget

        //查詢數據
        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());//輸出每一行數據
        }

 

以上。it

相關文章
相關標籤/搜索