Top Posts
Gửi mail trong Magento 2 – Đính kèm...
Tạo grid trong Magento 2 sử dụng block
Tạo form admin sử dụng block
Cách sử dụng insertListing trong Magento 2
Compile LESS file với Grunt trong Magento 2
Magento 2 get product image url
Format price với currency trong Magento 2
Magento 2 Add URL Rewrite programmatically
Magento 2 Upload image admin form
Magento 2 Create Category Attribute
vi-magento.com
  • Magento 2
    • Magento 2 cơ bản
    • Bài tập Magento 2
    • Magento 2 Api
  • PHP
  • JavaScript
  • Cơ sở dữ liệu
    • Học MongoDB
    • SQL Server
    • Mysql
    • Học Oracle
    • SQLite
  • Liên hệ
  • Trắc nghiệm Magento 2
Trang chủ Cơ sở dữ liệuHọc MongoDB MongoDB – Java
Học MongoDB

MongoDB – Java

bởi admin 17/07/2021
bởi admin 17/07/2021 0 Bình luận 94 xem

Danh mục

  1. Cài đặt
  2. Kết nối tới Database
  3. Tạo một Collection
  4. Lấy/chọn một Collection
  5. Chèn một Document
  6. Lấy tất cả Document
  7. Cập nhật Document
  8. Xóa Document đầu tiên

Cài đặt

Trước khi bắt đầu sử dụng MongoDB trong các chương trình Java, bạn cần đảm bảo đã có MongoDB JDBC Driver và Java cài đặt trên máy. Bạn có thể vào loạt bài Java để cài đặt Java trên máy cho mình. Bây giờ, chúng ta cần cài đặt MongoDB JDBC Driver.

  • Bạn cần tải jar từ Tải mongo.jar. Bạn nên tải phiên bản mới nhất.
  • Bạn cần bao mongo.jar vào trong Classpath.

Kết nối tới Database

Để kết nối Database, bạn cần xác định tên của 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ó.

Dưới đây là code để kết nối Database:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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() );
      }
   }
}
 

Biên dịch và chạy chương trình trên để tạo cơ sở dữ liệu. Bạn có thể thay đổi path tùy theo yêu cầu. Giả sử phiên bản hiện tại của JDBC Driver là mongo-2.10.1.jar là có sẵn trong path hiện tại.

1
2
3
4
5
6
 
$javac MongoDBJDBC.java
$java -classpath ".:mongo-2.10.1.jar" MongoDBJDBC
Connect to database successfully
Authentication: true
 

Nếu bạn đang sử dụng Windows, thì bạn có thể biên dịch và chạy code như sau:

1
2
3
4
5
6
 
$javac MongoDBJDBC.java
$java -classpath ".;mongo-2.10.1.jar" MongoDBJDBC
Connect to database successfully
Authentication: true
 

Giá trị của auth sẽ là true, nếu username và password là hợp lệ cho Database đã chọn.

Tạo một Collection

Để tạo một Collection, bạn sử dụng phương thức createCollection() của lớp com.mongodb.DB.

Bạn theo dõi code sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 
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() );
      }
   }
}
 

Khi chương trình được biên dịch và thực thi, kết quả là:

1
2
3
4
5
 
Connect to database successfully
Authentication: true
Collection created successfully
 

Lấy/chọn một Collection

Để lấy/chọn một Collection từ Database, bạn sử dụng phương thức getCollection() của lớp com.mongodb.DBCollection.

Bạn theo dõi code sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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() );
      }
   }
}
 

Khi chương trình được biên dịch và thực thi, kết quả là:

1
2
3
4
5
6
 
Connect to database successfully
Authentication: true
Collection created successfully
Collection mycol selected successfully
 

Chèn một Document

Để chèn một Document vào trong MongoDB, bạn sử dụng phương thức insert() của lớp com.mongodb.DBCollection.

Bạn theo dõi code sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 
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");
         BasicDBObject doc = new BasicDBObject("title", "MongoDB").
            append("description", "database").
            append("likes", 100).
            append("url", "http://www.tutorialspoint.com/mongodb/").
            append("by", "tutorials point");
         coll.insert(doc);
         System.out.println("Document inserted successfully");
      }catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
}
 

Khi chương trình được biên dịch và thực thi, kết quả là:

1
2
3
4
5
6
 
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Document inserted successfully
 

Lấy tất cả Document

Để chọn tất cả Document từ Collection, bạn sử dụng phương thức find() của lớp com.mongodb.DBCollection. Phương thức này trả về một con trỏ, vì thế bạn cần lặp qua con trỏ này.

Bạn theo dõi code sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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() );
      }
   }
}
 

Khi chương trình được biên dịch và thực thi, kết quả là:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Inserted Document: 1
{
   "_id" : ObjectId(7df78ad8902c),
   "title": "MongoDB",
   "description": "database",
   "likes": 100,
   "url": "http://www.tutorialspoint.com/mongodb/",
   "by": "tutorials point"
}
 

Cập nhật Document

Để cập nhật Document từ Collection, bạn sử dụng phương thức update() của lớp com.mongodb.DBCollection.

Bạn theo dõi code sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 
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() );
      }
   }
}
 

Khi chương trình được biên dịch và thực thi, kết quả là:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
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"
}
 

Xóa Document đầu tiên

Để xóa Document đầu tiên từ Collection, đầu tiên bạn cần chọn các Document bởi sử dụng phương thức findOne() và sau đó sử dụng phương thức remove của lớp com.mongodb.DBCollection.

Bạn theo dõi code sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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() );
      }
   }
}
 

Khi chương trình được biên dịch và thực thi, kết quả là:

1
2
3
4
5
6
 
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Document deleted successfully
 

Các phương thức save(), limit(), skip(), sort(), … của MongoDB làm việc tương tự như đã được giải thích ở trên.

MongoDB - JavaSử dụng MongoDB
Chia sẻ
0
FacebookSkype
Bài trước
MongoDB – PHP
Bài tiếp theo
MongoDB Deployment

Related Posts

Cài đặt MongoDB trên Windows

17/07/2021

Replica Set trong MongoDB

17/07/2021

Hoạt động chỉ mục nâng cao trong MongoDB

17/07/2021

Covered Query trong MongoDB

17/07/2021

Shard trong MongoDB

17/07/2021

MongoDB Deployment

17/07/2021

Phân tích truy vấn trong MongoDB

17/07/2021

Relationship trong MongoDB

17/07/2021
0 0 vote
Đánh giá
Login
guest
guest
0 Comments
Inline Feedbacks
View all comments

Bài viết cùng chủ đề

  • GridFS trong MongoDB

  • Làm việc với Rockmongo

  • Regular Expression trong MongoDB

  • Text Search trong MongoDB

  • Map Reduce trong MongoDB

  • ObjectId trong MongoDB

  • Hạn chế của chỉ mục trong MongoDB

  • Hoạt động chỉ mục nâng cao trong MongoDB

  • Hoạt động nguyên tử (Atomic Operation) trong MongoDB

  • Phân tích truy vấn trong MongoDB

  • Covered Query trong MongoDB

  • Tham chiếu Database trong MongoDB

  • Relationship trong MongoDB

  • MongoDB – PHP

  • MongoDB Deployment

  • Tạo Backup trong MongoDB

  • Shard trong MongoDB

  • Replica Set trong MongoDB

  • Aggregation trong MongoDB

  • Chỉ mục (Index) trong MongoDB

  • Sắp xếp bản ghi trong MongoDB

  • Giới hạn bản ghi trong MongoDB

  • Projection trong MongoDB

  • Xóa Document trong MongoDB

  • Cập nhật Document trong MongoDB

  • Truy vấn Document trong MongoDB

  • Chèn Document trong MongoDB

  • Kiểu dữ liệu trong MongoDB

  • Xóa Collection trong MongoDB

  • Tạo Collection trong MongoDB

  • Xóa Database trong MongoDB

  • Tạo Database trong MongoDB

  • Mô hình hóa dữ liệu trong MongoDB

  • Cài đặt MongoDB trên Windows

  • Lợi thế của MongoDB

  • Tổng quan về MongoDB

@2020 - All Right Reserved. vi-magento.com

vi-magento.com
  • Magento 2
    • Magento 2 cơ bản
    • Bài tập Magento 2
    • Magento 2 Api
  • PHP
  • JavaScript
  • Cơ sở dữ liệu
    • Học MongoDB
    • SQL Server
    • Mysql
    • Học Oracle
    • SQLite
  • Liên hệ
  • Trắc nghiệm Magento 2
wpDiscuz