MongoDB-mongo基礎操作
1、引入jar包 <!-- 載入MongoDB驅動包 --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.8.0</version> </dependency>
2、java中的基本呼叫 獲取mongodbDB地址(ServerAddress)->獲取mongoDB證書(MongoCredential,使用者名稱、資料庫名、密碼)->連線mongoDB服務(MongoClient)->連線資料庫(MongoDatabase)->操作資料庫 //連線到MongoDB服務 如果是遠端連線可以替換“localhost”為伺服器所在IP地址 //ServerAddress()兩個引數分別為 伺服器地址 和 埠 ServerAddress serverAddress = new ServerAddress("localhost",27017); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); //MongoCredential.createScramSha1Credential()三個引數分別為 使用者名稱 資料庫名稱 密碼 MongoCredential credential = MongoCredential.createScramSha1Credential("test", "test", "test".toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); //通過連線認證獲取MongoDB連線 MongoClient mongoClient = new MongoClient(addrs,credentials); //連線到資料庫 MongoDatabase mongoDatabase = mongoClient.getDatabase("test"); // mongoDatabase.createCollection("javaCollection"); //System.out.println("create collection successfully"); Document document = new Document(); document.append("javaTest", "javaTest"); mongoDatabase.getCollection("javaCollection").insertOne(document); FindIterable<Document> findIterable = mongoDatabase.getCollection("javaCollection").find(); MongoCursor<Document> cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); }