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.