在本章中,我们将学习如何设置和使用mongodb jdbc驱动程序。
要在java程序中使用mongodb之前,需要确保在机器上设置了mongodb jdbc驱动程序和java。 可以在机器上检查java环境可通过:java教程。 现在,我们来看一下如何设置mongodb jdbc驱动。
要连接数据库,需要指定数据库名称,如果数据库不存在,那么mongodb会自动创建它。
使用 eclipse 创建一个 maven 工程 - mongodbjdbc ,其目录结果如下所示 -
有关 pom.xml
文件的内容如下 -
<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelversion>4.0.0</modelversion>
<groupid>com.h3</groupid>
<artifactid>mongodbjdbc</artifactid>
<version>0.0.1-snapshot</version>
<packaging>jar</packaging>
<name>mongodbjdbc</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceencoding>utf-8</project.build.sourceencoding>
</properties>
<dependencies>
<dependency>
<groupid>junit</groupid>
<artifactid>junit</artifactid>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupid>org.mongodb</groupid>
<artifactid>mongodb-driver</artifactid>
<version>3.4.2</version>
</dependency>
</dependencies>
<build>
<defaultgoal>compile</defaultgoal>
</build>
</project>
以下是连接到数据库的代码片段 -
package com.h3.mongodbjdbc;
/**
* hello world!
*
*/
import com.mongodb.mongoclient;
import com.mongodb.client.mongodatabase;
public class app {
public static void main(string args[]) {
try {
// to connect to mongodb server
mongoclient mongoclient = new mongoclient("localhost", 27017);
// now connect to your databases
mongodatabase mgdb = mongoclient.getdatabase("mycol");
system.out.println("connect to database successfully!");
system.out.println("mongodatabase inof is : "+mgdb.getname());
// if mongodb in secure mode, authentication is required.
// boolean auth = db.authenticate(myusername, mypassword);
// system.out.println("authentication: "+auth);
} catch (exception e) {
system.err.println(e.getclass().getname() + ": " + e.getmessage());
}
}
}
默认认证机制
string user; // the user name
string database; // the name of the database in which the user is defined
char[] password; // the password as a character array
// ...
mongocredential credential = mongocredential.createcredential(user, database, password);
mongoclient mongoclient = new mongoclient(new serveraddress("host1", 27017),
arrays.aslist(credential));
或者使用连接字符串而不明确指定认证机制:
mongoclienturi uri = new mongoclienturi("mongodb://user1:pwd1@host1/?authsource=db1");
mongoclient mongoclient = new mongoclient(uri);
执行上面代码,得到以下结果 -
com.mongodb.diagnostics.logging.jullogger log
信息: cluster created with settings {hosts=[localhost:27017], mode=single, requiredclustertype=unknown, serverselectiontimeout='30000 ms', maxwaitqueuesize=500}
connect to database successfully!
mongodatabase inof is : mycol
要创建集合,可使用 com.mongodb.db
类的 createcollection()
方法。
以下是创建集合的代码片段 -
package com.h3.mongodbjdbc;
import org.bson.document;
import com.mongodb.dbcollection;
import com.mongodb.client.model.createcollectionoptions;
/**
* hello world!
*
*/
import com.mongodb.mongoclient;
import com.mongodb.client.mongocollection;
import com.mongodb.client.mongodatabase;
public class createcollection {
public static void main(string args[]) {
try {
// to connect to mongodb server
mongoclient mongoclient = new mongoclient("localhost", 27017);
// now connect to your databases
mongodatabase database = mongoclient.getdatabase("test");
//database.createcollection("newcollection",new createcollectionoptions().capped(true).sizeinbytes(0x100000));
mongocollection<document> coll = database.getcollection("mytestcollection");
system.out.println("collection created successfully");
system.out.println("当前数据库中的所有集合是:");
for (string name : database.listcollectionnames()) {
system.out.println(name);
}
} catch (exception e) {
system.err.println(e.getclass().getname() + ": " + e.getmessage());
}
}
}
执行上面代码,得到以下结果 -
collection created successfully
当前数据库中的所有集合是:
mycol
inventory
post
mycollection
newcollection
要将文档插入到mongodb中,使用com.mongodb.dbcollection
类的insertone()
方法。
以下是插入文档的代码片段 -
package com.h3.mongodbjdbc;
import java.util.arrays;
import org.bson.document;
import com.mongodb.basicdbobject;
import com.mongodb.block;
import com.mongodb.dbcollection;
import com.mongodb.dbcursor;
/**
* hello world!
*
*/
import com.mongodb.mongoclient;
import com.mongodb.client.mongocollection;
import com.mongodb.client.mongocursor;
import com.mongodb.client.mongodatabase;
import com.mongodb.client.model.createcollectionoptions;
public class insertdocument {
public static void main(string args[]) {
try {
// to connect to mongodb server
mongoclient mongoclient = new mongoclient("localhost", 27017);
// now connect to your databases
mongodatabase database = mongoclient.getdatabase("test");
// database.createcollection("newcollection", new
// createcollectionoptions().capped(true).sizeinbytes(0x100000));
system.out.println("collection created successfully");
system.out.println("当前数据库中的所有集合是:");
for (string name : database.listcollectionnames()) {
system.out.println(name);
}
mongocollection coll = database.getcollection("mycol");
system.out.println("collection mycol selected successfully");
mongocollection<document> collection = database.getcollection("mycol");
document document = new document("_id", 1999).append("title", "mongodb insert demo")
.append("description","database")
.append("likes", 30)
.append("by", "h3 point")
.append("url", "http://www.h3.com/mongodb/");
collection.insertone(document);
collection.find().foreach(printblock);
system.out.println("document inserted successfully");
} catch (exception e) {
system.err.println(e.getclass().getname() + ": " + e.getmessage());
}
}
static block<document> printblock = new block<document>() {
public void apply(final document document) {
system.out.println(document.tojson());
}
};
}
执行上面代码,得到以下结果 -
newcollection
mycol
inventory
post
collection
mycollection
newcollection
collection mycol selected successfully
{ "_id" : 123.0, "title" : "mongodb overview", "description" : "mongodb is no sql database", "by" : "h3 tutorials", "url" : "http://www.h3.com", "tags" : ["mongodb", "database", "nosql"], "likes" : 100.0 }
{ "_id" : 100.0, "title" : "mongodb overview", "description" : "mongodb is no sql database", "by" : "h3 tutorials", "url" : "http://www.h3.com", "tags" : ["mongodb", "database", "nosql"], "likes" : 100.0 }
{ "_id" : 1999, "title" : "mongodb insert demo", "description" : "database", "likes" : 30, "by" : "h3 point", "url" : "http://www.h3.com/mongodb/" }
document inserted successfully
如何插入多行?
document doc1 = new document("name", "amarcord pizzeria")
.append("contact", new document("phone", "264-555-0193")
.append("email", "amarcord.pizzeria@example.net")
.append("location",arrays.aslist(-73.88502, 40.749556)))
.append("stars", 2)
.append("categories", arrays.aslist("pizzeria", "italian", "pasta"));
document doc2 = new document("name", "blue coffee bar")
.append("contact", new document("phone", "604-555-0102")
.append("email", "bluecoffeebar@example.com")
.append("location",arrays.aslist(-73.97902, 40.8479556)))
.append("stars", 5)
.append("categories", arrays.aslist("coffee", "pastries"));
list<document> documents = new arraylist<document>();
documents.add(doc1);
documents.add(doc2);
collection.insertmany(documents);
要从集合更新文档,使用com.mongodb.dbcollection
类的update()
和updatemany()
方法。以下是选择第一个文档的代码片段 -
package com.h3.mongodbjdbc;
import org.bson.document;
import com.mongodb.block;
/**
* hello world!
*
*/
import com.mongodb.mongoclient;
import com.mongodb.mongoclienturi;
import com.mongodb.serveraddress;
import com.mongodb.client.mongodatabase;
import com.mongodb.client.mongocollection;
import org.bson.document;
import com.mongodb.client.mongocursor;
import static com.mongodb.client.model.filters.*;
import com.mongodb.client.result.deleteresult;
import static com.mongodb.client.model.updates.*;
import com.mongodb.client.result.updateresult;
import java.util.arraylist;
import java.util.list;
public class app {
public static void main(string args[]) {
try {
// to connect to mongodb server
mongoclient mongoclient = new mongoclient("127.0.0.1", 27017);
// now connect to your databases
mongodatabase database = mongoclient.getdatabase("mycol");
system.out.println("connect to database successfully!");
system.out.println("mongodatabase inof is : "+database.getname());
mongocollection<document> collection = database.getcollection("mycol");
//collection.updateone(eq("_id", 1999),new document("$set", new document("title", "更新了标题2")));
document document = new document("_id", 9999).append("title", "mongodb insert demo")
.append("description","database")
.append("likes", 30)
.append("by", "h3 point")
.append("url", "http://www.h3.com/mongodb/");
collection.insertone(document);
collection.find().foreach(printblock);
collection.updateone(eq("_id", 9999),new document("$set", new document("title", "更新了标题2")));
collection.find().foreach(printblock);
} catch (exception e) {
system.err.println(e.getclass().getname() + ": " + e.getmessage());
}
}
static block<document> printblock = new block<document>() {
public void apply(final document document) {
system.out.println(document.tojson());
}
};
}
执行上面代码,得到以下结果 -
{ "_id" : 1999, "title" : "更新了标题2", "description" : "database", "likes" : 30, "by" : "h3 point", "url" : "http://www.h3.com/mongodb/" }
{ "_id" : 9999, "title" : "mongodb insert demo", "description" : "database", "likes" : 30, "by" : "h3 point", "url" : "http://www.h3.com/mongodb/" }
{ "_id" : 1999, "title" : "更新了标题2", "description" : "database", "likes" : 30, "by" : "h3 point", "url" : "http://www.h3.com/mongodb/" }
{ "_id" : 9999, "title" : "更新了标题2", "description" : "database", "likes" : 30, "by" : "h3 point", "url" : "http://www.h3.com/mongodb/" }
要从集合中删除第一个文档,需要首先使用findone()
方法选择文档,然后使用com.mongodb.dbcollection
类的remove()
方法。
以下是删除第一个文档的代码片段 -
package com.h3.mongodbjdbc;
import org.bson.document;
import com.mongodb.block;
/**
* hello world!
*
*/
import com.mongodb.mongoclient;
import com.mongodb.mongoclienturi;
import com.mongodb.serveraddress;
import com.mongodb.client.mongodatabase;
import com.mongodb.client.mongocollection;
import org.bson.document;
import com.mongodb.client.mongocursor;
import static com.mongodb.client.model.filters.*;
import com.mongodb.client.result.deleteresult;
import static com.mongodb.client.model.updates.*;
import com.mongodb.client.result.updateresult;
import java.util.arraylist;
import java.util.list;
public class app {
public static void main(string args[]) {
try {
// to connect to mongodb server
mongoclient mongoclient = new mongoclient("127.0.0.1", 27017);
// now connect to your databases
mongodatabase database = mongoclient.getdatabase("mycol");
system.out.println("connect to database successfully!");
system.out.println("mongodatabase inof is : "+database.getname());
// 更新文档
mongocollection<document> collection = database.getcollection("mycol");
/**
document document = new document("_id", 9999).append("title", "mongodb insert demo")
.append("description","database")
.append("likes", 30)
.append("by", "h3 point")
.append("url", "http://www.h3.com/mongodb/");
collection.insertone(document);
//collection.find().foreach(printblock);
//collection.updateone(eq("_id", 9999),new document("$set", new document("title", "更新了标题2")));
*/
collection.find().foreach(printblock);
// 删除文档
collection.deleteone(eq("_id", 9999));
system.out.println("after delete document:");
collection.find().foreach(printblock);
} catch (exception e) {
system.err.println(e.getclass().getname() + ": " + e.getmessage());
}
}
static block<document> printblock = new block<document>() {
public void apply(final document document) {
system.out.println(document.tojson());
}
};
}
执行上面代码,得到以下结果 -
{ "_id" : 1999, "title" : "更新了标题2", "description" : "database", "likes" : 30, "by" : "h3 point", "url" : "http://www.h3.com/mongodb/" }
{ "_id" : 9999, "title" : "更新了标题2", "description" : "database", "likes" : 30, "by" : "h3 point", "url" : "http://www.h3.com/mongodb/" }
after delete document:
{ "_id" : 1999, "title" : "更新了标题2", "description" : "database", "likes" : 30, "by" : "h3 point", "url" : "http://www.h3.com/mongodb/" }