1. 程式人生 > >Java中使用mongodb實現增刪改查

Java中使用mongodb實現增刪改查

Java

安裝

要想在 Java 程式中使用 MongoDB,需要先確定是否安裝了 MongoDB JDBC 驅動,並且要在機器上安裝了 Java。檢視 Java 教程來確保在機器上安裝好 Java。下面來介紹如何安裝 MongoDB JDBC 驅動。

  • 從路徑 Download mongo.jar 處下載 jar 檔案,注意下載最新版本。
  • 在類路徑中包括 mongo.jar 檔案。

連線資料庫

為了連線資料庫,需要指定資料庫名稱,如果資料庫不存在,mongodb 就會自動建立它。

連線資料庫的程式碼段如下所示:

複製程式碼 複製程式碼
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC{
   public static void main( String args[] ){
      try{   
         // To connect to mongodb server
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // Now connect to your databases
         DB db = mongoClient.getDB( "test" );
         System.out.println("Connect to database successfully");
         boolean auth = db.authenticate(myUserName, myPassword);
         System.out.println("Authentication: "+auth);
      }catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
}
複製程式碼 複製程式碼

下面編譯並執行上面的程式,以便測試資料庫。可以針對每個需求改變路徑。假設當前 JDBC 驅動版本 mongo-2.10.1.jar 可用於當前路徑。

$javac MongoDBJDBC.java
$java -classpath ".:mongo-2.10.1.jar" MongoDBJDBC
Connect to database successfully
Authentication: true

如果想使用 Windows 系統的機器,則編譯並執行程式碼如下:

$javac MongoDBJDBC.java
$java -classpath ".;mongo-2.10.1.jar" MongoDBJDBC
Connect to database successfully
Authentication: true

如果選定資料庫的使用者名稱及密碼有效,則 auth 值為 true。

建立集合

建立集合需要使用 com.mongodb.DB 類的 createCollection() 方法。

建立集合的程式碼段如下所示:

複製程式碼 複製程式碼
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC{
   public static void main( String args[] ){
      try{   
     // To connect to mongodb server
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // Now connect to your databases
         DB db = mongoClient.getDB( "test" );
     System.out.println("Connect to database successfully");
         boolean auth = db.authenticate(myUserName, myPassword);
     System.out.println("Authentication: "+auth);
         DBCollection coll = db.createCollection("mycol");
         System.out.println("Collection created successfully");
      }catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
}
複製程式碼 複製程式碼

編譯並執行該程式,結果如下所示:

Connect to database successfully
Authentication: true
Collection created successfully

獲取/選擇一個集合

從資料庫中獲取/選擇一個集合,使用 com.mongodb.DBCollection 類的 getCollection() 方法。程式碼段如下:

複製程式碼 複製程式碼
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC{
   public static void main( String args[] ){
      try{   
     // To connect to mongodb server
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // Now connect to your databases
         DB db = mongoClient.getDB( "test" );
     System.out.println("Connect to database successfully");
         boolean auth = db.authenticate(myUserName, myPassword);
     System.out.println("Authentication: "+auth);
         DBCollection coll = db.createCollection("mycol");
         System.out.println("Collection created successfully");
         DBCollection coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
      }catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
}
複製程式碼 複製程式碼

編譯並執行該程式,結果如下所示:

Connect to database successfully
Authentication: true
Collection created successfully
Collection mycol selected successfully

插入文件

插入文件使用 com.mongodb.DBCollection 類的 insert() 方法。程式碼段如下所示:

複製程式碼 複製程式碼
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC{
   public static void main( String args[] ){
      try{   
     // To connect to mongodb server
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // Now connect to your databases
         DB db = mongoClient.getDB( "test" );
     System.out.println("Connect to database successfully");
         boolean auth = db.authenticate(myUserName, myPassword);
     System.out.println("Authentication: "+auth);         
         DBCollection coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
         DBCursor cursor = coll.find();
         int i=1;
         while (cursor.hasNext()) { 
            System.out.println("Inserted Document: "+i); 
            System.out.println(cursor.next()); 
            i++;
         }
      }catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
}
複製程式碼 複製程式碼

編譯並執行該程式,結果如下所示

Connect to database successfully
Authentication: true
Collection mycol selected successfully
Document inserted successfully

檢索所有文件

選擇集合中的所有文件,使用 com.mongodb.DBCollection 類的 find() 方法。該方法返回一個遊標,所以需要迭代該遊標。

選擇所有文件的程式碼如下所示:

複製程式碼 複製程式碼
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC{
   public static void main( String args[] ){
      try{   
     // To connect to mongodb server
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // Now connect to your databases
         DB db = mongoClient.getDB( "test" );
     System.out.println("Connect to database successfully");
         boolean auth = db.authenticate(myUserName, myPassword);
     System.out.println("Authentication: "+auth);         
         DBCollection coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
         DBCursor cursor = coll.find();
         while (cursor.hasNext()) { 
            DBObject updateDocument = cursor.next();
            updateDocument.put("likes","200")
            col1.update(updateDocument); 
         }
         System.out.println("Document updated successfully");
         cursor = coll.find();
         int i=1;
         while (cursor.hasNext()) { 
            System.out.println("Updated Document: "+i); 
            System.out.println(cursor.next()); 
            i++;
         }
      }catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
}
複製程式碼 複製程式碼

編譯並執行程式的結果如下:

複製程式碼 複製程式碼
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Document updated successfully
Updated Document: 1
{
   "_id" : ObjectId(7df78ad8902c),
   "title": "MongoDB",
   "description": "database",
   "likes": 100,
   "url": "http://www.tutorialspoint.com/mongodb/",
   "by": "tutorials point"
}
複製程式碼 複製程式碼

更新文件

更新集合中的文件,使用 com.mongodb.DBCollection 類的 update() 方法。程式碼如下所示:

複製程式碼 複製程式碼
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC{
   public static void main( String args[] ){
      try{   
     // To connect to mongodb server
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // Now connect to your databases
         DB db = mongoClient.getDB( "test" );
     System.out.println("Connect to database successfully");
         boolean auth = db.authenticate(myUserName, myPassword);
     System.out.println("Authentication: "+auth);         
         DBCollection coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
         DBCursor cursor = coll.find();
         while (cursor.hasNext()) { 
            DBObject updateDocument = cursor.next();
            updateDocument.put("likes","200")
            col1.update(updateDocument); 
         }
         System.out.println("Document updated successfully");
         cursor = coll.find();
         int i=1;
         while (cursor.hasNext()) { 
            System.out.println("Updated Document: "+i); 
            System.out.println(cursor.next()); 
            i++;
         }
      }catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
}
複製程式碼 複製程式碼

程式編譯及執行結果如下:

複製程式碼 複製程式碼
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Document updated successfully
Updated Document: 1
{
   "_id" : ObjectId(7df78ad8902c),
   "title": "MongoDB",
   "description": "database",
   "likes": 100,
   "url": "http://www.tutorialspoint.com/mongodb/",
   "by": "tutorials point"
}
複製程式碼 複製程式碼

刪除第一個文件

刪除集合中的第一個文件,需要使用 findOne() 方法選中第一個文件,然後使用 com.mongodb.DBCollection 類的remove 方法將其刪除。程式碼範例如下:

複製程式碼 複製程式碼
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC{
   public static void main( String args[] ){
      try{   
     // To connect to mongodb server
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // Now connect to your databases
         DB db = mongoClient.getDB( "test" );
     System.out.println("Connect to database successfully");
         boolean auth = db.authenticate(myUserName, myPassword);
     System.out.println("Authentication: "+auth);         
         DBCollection coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
         DBObject myDoc = coll.findOne();
         col1.remove(myDoc);
         DBCursor cursor = coll.find();
         int i=1;
         while (cursor.hasNext()) { 
            System.out.println("Inserted Document: "+i); 
            System.out.println(cursor.next()); 
            i++;
         }
         System.out.println("Document deleted successfully");
      }catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
}
複製程式碼 複製程式碼