MongoDB Java

2022-09-06 17:12 更新

環(huán)境配置

在Java程序中如果要使用MongoDB,你需要確保已經(jīng)安裝了Java環(huán)境及MongoDB JDBC 驅(qū)動。

你可以參考本站的 Java教程來安裝Java程序?,F(xiàn)在讓我們來檢測你是否安裝了 MongoDB JDBC 驅(qū)動。

  • 首先你必須下載mongo jar包,下載地址: https://github.com/mongodb/mongo-java-driver/downloads, 請確保下載最新版本。
  • 你需要將mongo.jar包含在你的 classpath 中。

連接數(shù)據(jù)庫

連接數(shù)據(jù)庫,你需要指定數(shù)據(jù)庫名稱,如果指定的數(shù)據(jù)庫不存在,mongo會自動創(chuàng)建數(shù)據(jù)庫。

連接數(shù)據(jù)庫的Java代碼如下:

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{   
		 // 連接到 mongodb 服務(wù)
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // 連接到數(shù)據(jù)庫
         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() );
	  }
   }
}

現(xiàn)在,讓我們來編譯運行程序并創(chuàng)建數(shù)據(jù)庫test。

你可以更加你的實際環(huán)境改變MongoDB JDBC驅(qū)動的路徑。

本實例將MongoDB JDBC啟動包 mongo-2.10.1.jar 放在本地目錄下:

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

如果你使用的是Window系統(tǒng),你可以按以下命令來編譯執(zhí)行程序:

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

如果用戶名及密碼正確,則Authentication 的值為true。


創(chuàng)建集合

我們可以使用com.mongodb.DB類中的createCollection()來創(chuàng)建集合

代碼片段如下:

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{   
	     // 連接到 mongodb 服務(wù)
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // 連接到數(shù)據(jù)庫
         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() );
	  }
   }
}

編譯運行以上程序,輸出結(jié)果如下:

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{   
	     // 連接到 mongodb 服務(wù)
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // 連接到數(shù)據(jù)庫
         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() );
	  }
   }
}

編譯運行以上程序,輸出結(jié)果如下:

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{   
		 // 連接到 mongodb 服務(wù)
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // 連接到數(shù)據(jù)庫
         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");
         BasicDBObject doc = new BasicDBObject("title", "MongoDB").
            append("description", "database").
            append("likes", 100).
            append("url", "http://m.hgci.cn/mongodb/").
            append("by", "w3cschool.cn");
         coll.insert(doc);
         System.out.println("Document inserted successfully");
      }catch(Exception e){
	     System.err.println( e.getClass().getName() + ": " + e.getMessage() );
	  }
   }
}

編譯運行以上程序,輸出結(jié)果如下:

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

檢索所有文檔

我們可以使用com.mongodb.DBCollection類中的 find() 方法來獲取集合中的所有文檔。

此方法返回一個游標(biāo),所以你需要遍歷這個游標(biāo)。

代碼片段如下:

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{   
		// 連接到 mongodb 服務(wù)
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
          // 連接到數(shù)據(jù)庫
         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() );
	  }
   }
}

編譯運行以上程序,輸出結(jié)果如下:

Connect to database successfully
Authentication: true
Collection mycol selected successfully
Inserted Document: 1
{
   "_id" : ObjectId(7df78ad8902c),
   "title": "MongoDB",
   "description": "database",
   "likes": 100,
   "url": "http://m.hgci.cn/mongodb/",
   "by": "w3cschool.cn"
}

更新文檔

你可以使用 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{   
	 // 連接到Mongodb服務(wù)
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // 連接到你的數(shù)據(jù)庫
         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")
            coll.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() );
	  }
   }
}

編譯運行以上程序,輸出結(jié)果如下:

Connect to database successfully
Authentication: true
Collection mycol selected successfully
Document updated successfully
Updated Document: 1
{
   "_id" : ObjectId(7df78ad8902c),
   "title": "MongoDB",
   "description": "database",
   "likes": 200,
   "url": "http://m.hgci.cn/mongodb/",
   "by": "w3cschool.cn"
}

刪除第一個文檔

要刪除集合中的第一個文檔,首先你需要使用com.mongodb.DBCollection類中的 findOne()方法來獲取第一個文檔,然后使用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{   
	 // 連接到Mongodb服務(wù)
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         // 連接到你的數(shù)據(jù)庫
         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();
         coll.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() );
	  }
   }
}

編譯運行以上程序,輸出結(jié)果如下:

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

你還可以使用 save(), limit(), skip(), sort() 等方法來操作MongoDB數(shù)據(jù)庫。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號