Bài 23: MongoDB - Java(P1) - MongoDB

Đăng bởi: Admin | Lượt xem: 1341 | Chuyên mục: SQL


Trong bài hôm nay, chúng ta cùng tìm hiểu làm thế nào để cài đặt MongoDB CLIENT.

1. Cài đặt :

Trước khi bắt đầu sử dụng MongoDB trong các chương trình Java của mình, bạn cần đảm bảo rằng bạn đã thiết lập MongoDB CLIENT và Java trên máy. Bạn có thể xem hướng dẫn Java để cài đặt Java trên máy của bạn. Bây giờ, chúng ta hãy kiểm tra cách thiết lập MongoDB CLIENT.
  • Cần phải dowbload mongodb-driver-3.11.2.jar và its dependency mongodb-driver-core-3.11.2.jar. Cài đặt phiên bản mới nhất
  • Bạn cần đưa các tệp jar đã tải xuống vào đường dẫn classpath của mình.

2. Kết nối tới Database

Để kết nối cơ sở dữ liệu, bạn cần chỉ định tên cơ sở dữ liệu, nếu cơ sở dữ liệu không tồn tại thì MongoDB sẽ tự động tạo nó.
Sau đây là đoạn code để kết nối với cơ sở dữ liệu -
import com.mongodb.client.MongoDatabase; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class ConnectToDB { 
   
   public static void main( String args[] ) {  
      
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
   
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb"); 
      System.out.println("Credentials ::"+ credential);     
   } 
}
Bây giờ, hãy biên dịch và chạy chương trình trên để tạo cơ sở dữ liệu myDb như sau :
$javac ConnectToDB.java 
$java ConnectToDB
Khi thực thi, chương trình trên cung cấp cho bạn kết quả sau.
Connected to the database successfully 
Credentials ::MongoCredential{
   mechanism = null, 
   userName = 'sampleUser', 
   source = 'myDb', 
   password = <hidden>, 
   mechanismProperties = {}
}

3. Tạo Collection

Để tạo collection, phương thức createCollection () của lớp com.mongodb.client.MongoDatabase được sử dụng.
Sau đây là đoạn code để tạo collection :
import com.mongodb.client.MongoDatabase; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class CreatingCollection { 
   
   public static void main( String args[] ) {  
      
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
     
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      //Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      //Creating a collection 
      database.createCollection("sampleCollection"); 
      System.out.println("Collection created successfully"); 
   } 
}
Khi biên dịch, chương trình trên cho bạn kết quả sau:
Connected to the database successfully 
Collection created successfully

4. Lấy / Chọn collection

Để lấy / chọn một collection từ cơ sở dữ liệu, phương thức getCollection () của lớp com.mongodb.client.MongoDatabase được sử dụng.
import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoDatabase; 
import org.bson.Document; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class selectingCollection { 
   
   public static void main( String args[] ) {  
      
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
     
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      // Creating a collection 
      System.out.println("Collection created successfully"); 
      // Retrieving a collection
      MongoCollection<Document> collection = database.getCollection("myCollection"); 
      System.out.println("Collection myCollection selected successfully"); 
   }
}
Kết quả :
Connected to the database successfully 
Collection created successfully 
Collection myCollection selected successfully

5.Thêm Document:


103/5000Để chèn một tài liệu vào MongoDB, phương thức insert () của lớp com.mongodb.client.MongoCollection được sử dụng.
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
public class InsertingDocument {
	public static void main( String args[] ) {
	
	// Creating a Mongo client
	MongoClient mongo = new MongoClient( "localhost" , 27017 );
	
	// Accessing the database
	MongoDatabase database = mongo.getDatabase("myDb");
	
	// Creating a collection
	database.createCollection("sampleCollection");
	System.out.println("Collection created successfully");
	
	// Retrieving a collection
	MongoCollection<Document> collection = database.getCollection("sampleCollection");
	System.out.println("Collection sampleCollection selected successfully");
	Document document = new Document("title", "MongoDB")
	.append("description", "database")
	.append("likes", 100)
	.append("url", "http://www.tutorialspoint.com/mongodb/")
	.append("by", "tutorials point");
	
	//Inserting document into the collection
	collection.insertOne(document);
	System.out.println("Document inserted successfully");
}
Kết quả như sau :
Connected to the database successfully 
Collection sampleCollection selected successfully 
Document inserted successfully
Bài tiếp theo: MongoDB - Java(p2) >>
vncoder logo

Theo dõi VnCoder trên Facebook, để cập nhật những bài viết, tin tức và khoá học mới nhất!