本文为学习mongodb for java 翻译的是官方文档
MongoDB Driver Quick Tour
Make a Connection
下面的例子将会为我们展示连接到database mydb的5种方法,如果这个数据库不存在,那么将会为我们创建这个数据库
<span style="font-size: 14px;">// To directly connect to a single MongoDB server
// (this will not auto-discover the primary even if it's a member of a replica set)
MongoClient mongoClient = new MongoClient();
// or
MongoClient mongoClient = new MongoClient( "localhost" );
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
MongoClient mongoClient = new MongoClient(
Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
// or use a connection string
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019");
MongoClient mongoClient = new MongoClient(connectionString);
MongoDatabase database = mongoClient.getDatabase("mydb");</span>
这时 我们已经建立了与特定数据库的连接
MongoClient
MongoClient 代表了一个与数据库连接池的实例,我们只需要一个MongoClient的实例即可
Get A Collection
为了获得一个特定的集合,我们需要指定集合的名称给getCollection方法
MongoCollection<Document> collection = database.getCollection("test");
Insert a Document
{
"name" : "MongoDB",
"type" : "database",
"count" : 1,
"info" : {
x : 203,
y : 102
}
}
利用Document类创建一个文档对象,
Document doc = new Document("name", "MongoDB")
.append("type", "database")
.append("count", 1)
.append("info", new Document("x", 203).append("y", 102));
To insert the document into the collection, use the
insertOne()
method.
collection.insertOne(doc);
Add Multiple Documents
To add multiple documents, you can use the insertMany()
method.
The following example will add multiple documents of the form:
{ "i" : value }
Create the documents in a loop.
List<Document> documents = new ArrayList<Document>();
for (int i = 0; i < 100; i++) {
documents.add(new Document("i", i));
}
To insert these documents to the collection, pass the list of documents to the insertMany()
method.
collection.insertMany(documents);
Count Documents in A Collection
System.out.println(collection.count());
Query the Collection
查询集合用find方法进行查询操作
Find the First Document in a Collection
为了获得collection中的第一个document,我们可以在find()方法后使用first()方法得到第一个document,collection.find().first(),将会返回第一个document或者null 而不是一个cursor,这对于我们的查询结果只有一个的情况,或者说只对第一个感兴趣的来说是一个很好的选择
下面的例子为我们展示集合中的第一个document
Document myDoc = collection.find().first();
System.out.println(myDoc.toJson());
这个例子的输出结果如下所示
{ "_id" : { "$oid" : "551582c558c7b4fbacf16735" },
"name" : "MongoDB", "type" : "database", "count" : 1,
"info" : { "x" : 203, "y" : 102 } }
Find All Documents in a Collection
为了检索一个collection中的所有的document,我们将会使用find()方法,这个方法返回值为FindIterable类型,使用iterator()方法获得一个迭代器Iterator,
MongoCursor<Document> cursor = collection.find().iterator();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
Get A Single Document with a Query Filter
我们可以创建一个过滤器来过滤find()的结果,例如
import static com.mongodb.client.model.Filters.*;
myDoc = collection.find(eq("i", 71)).first();
System.out.println(myDoc.toJson());
他的结果应该是一个document
{ "_id" : { "$oid" : "5515836e58c7b4fbc756320b" }, "i" : 71 }
Get a Set of Documents with a Query
collection.find(and(gt("i", 50), lte("i", 100)))
Sorting documents
我们可以用sort方法来对document排序sort()
method on a
FindIterableBelow we use the exists()
helper and sort descending("i")
helper to sort our documents:
myDoc = collection.find(exists("i")).sort(descending("i")).first();
System.out.println(myDoc.toJson());
Projecting fields
有时我们并不需要一个document中的所有数据,Projections可以帮助我们实现,在find()方法之后myDoc = collection.find().projection(excludeId()).first();
System.out.println(myDoc.toJson());
Updating documents
如果最多更新一个document我们可以用updateonde,当然如果没有条件匹配,更新的个数也可能是0,我们在这里更新第一个满足i=10的document
collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110)));
更新多条document我们使用updatemany(),我们在这里将小于100的都自增100
UpdateResult updateResult = collection.updateMany(lt("i", 100),
new Document("$inc", new Document("i", 100)));
System.out.println(updateResult.getModifiedCount());
UpdateResult提供了更新影响的行数也就是document个数
Deleting documents
collection.deleteOne(eq("i", 110))
DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
System.out.println(deleteResult.getDeletedCount());
MongoDB Driver Admin Quick Tour
在这一部分我们可以看到管理员的一些特殊属性和操作Setup
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("test");
Get A List of Databases
for (String name: mongoClient.listDatabaseNames()) {
System.out.println(name);
}
Drop A Database
mongoClient.getDatabase("databaseToBeDropped").drop();
Create A Collection
<span style="font-size: 14px;">database.createCollection("cappedCollection",
new CreateCollectionOptions().capped(true).sizeInBytes(0x100000)</span><span style="font-size: 24px;">);</span>
<span style="font-size: 14px;">database.createCollection("cappedCollection",
new CreateCollectionOptions().capped(true).sizeInBytes(0x100000)</span><span style="font-size: 24px;">);</span>
Get A List of Collections
<span style="font-size: 14px;">for (String name : database.listCollectionNames()) {
System.out.println(name);
}</span>
Drop A Collection
collection.dropCollection();
Create An Index
的创建索引,1代表升序,-1代表降序 collection.createIndex(new Document("i", 1));
collection.createIndex(new Document("i", 1));
Text indexes
mongodb还支持字符串内容的索引 coll.createIndex(new Document("content", "text"));
coll.createIndex(new Document("content", "text"));
Authentication
import com.mongodb.MongoCredential;
// ...
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);
CRUD
MongoCollection<Document> collection = database.getCollection("mycoll");
// insert a document
Document document = new Document("x", 1)
collection.insertOne(document);
document.append("x", 2).append("y", 3);
// replace a document
collection.replaceOne(Filters.eq("_id", document.get("_id")), document);
// find documents
List<Document> foundDocument = collection.find().into(new ArrayList<Document>());
单例模式获得mongoClient
<span style="font-size:14px;">private static Logger logger = Logger.getLogger(MongoDBDao.class);
/**
* MongoClient的实例代表数据库连接池,是线程安全的,可以被多线程共享,客户端在多线程条件下仅维持一个实例即可
* Mongo是非线程安全的,目前mongodb API中已经建议用MongoClient替代Mongo
*/
private MongoClient mongoClient = null;
/**
*
* 私有的构造函数
* 作者:shibin
*/
private MongoDBDao(){
if(mongoClient == null){
String url = Constant.MONGO_URL;
String user = Constant.MONGO_USER;
String password = Constant.MONGO_PASSWORD;
String database = Constant.MONGO_DATABASE;
int port = 27017;
ServerAddress serverAddress = new ServerAddress(url, port);
List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
serverAddresses.add(serverAddress);
MongoCredential credential = MongoCredential.createCredential(user, database, password.toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
mongoClient = new MongoClient(serverAddresses, credentials);
System.out.println(mongoClient);
System.out.println("初始化client完成");
}
}
/********单例模式声明开始,采用饿汉式方式生成,保证线程安全********************/
//类初始化时,自行实例化,饿汉式单例模式
private static final MongoDBDao mongoDBDao = new MongoDBDao();
/**
*
* 方法名:getMongoDBDaoImplInstance
* 作者:shibin
* 创建时间:2014-8-30 下午04:29:26
* 描述:单例的静态工厂方法
* @return
*/
public static MongoDBDao getMongoDBDaoInstance(){
return mongoDBDao;
}</span>
<span style="font-size:14px;">private static Logger logger = Logger.getLogger(MongoDBDao.class);
/**
* MongoClient的实例代表数据库连接池,是线程安全的,可以被多线程共享,客户端在多线程条件下仅维持一个实例即可
* Mongo是非线程安全的,目前mongodb API中已经建议用MongoClient替代Mongo
*/
private MongoClient mongoClient = null;
/**
*
* 私有的构造函数
* 作者:shibin
*/
private MongoDBDao(){
if(mongoClient == null){
String url = Constant.MONGO_URL;
String user = Constant.MONGO_USER;
String password = Constant.MONGO_PASSWORD;
String database = Constant.MONGO_DATABASE;
int port = 27017;
ServerAddress serverAddress = new ServerAddress(url, port);
List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
serverAddresses.add(serverAddress);
MongoCredential credential = MongoCredential.createCredential(user, database, password.toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
mongoClient = new MongoClient(serverAddresses, credentials);
System.out.println(mongoClient);
System.out.println("初始化client完成");
}
}
/********单例模式声明开始,采用饿汉式方式生成,保证线程安全********************/
//类初始化时,自行实例化,饿汉式单例模式
private static final MongoDBDao mongoDBDao = new MongoDBDao();
/**
*
* 方法名:getMongoDBDaoImplInstance
* 作者:shibin
* 创建时间:2014-8-30 下午04:29:26
* 描述:单例的静态工厂方法
* @return
*/
public static MongoDBDao getMongoDBDaoInstance(){
return mongoDBDao;
}</span>
示例程序
连接数据库
连接数据库,你需要指定数据库名称,如果指定的数据库不存在,mongo会自动创建数据库。
连接数据库的Java代码如下:
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
本实例中 Mongo 数据库无需用户名密码验证。如果你的 Mongo 需要验证用户名及密码,可以使用以下代码:
import java.util.ArrayList;
import java.util.List;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String[] args){
try {
//连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
//ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress("localhost",27017);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(addrs,credentials);
//连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
System.out.println("Connect to database successfully");
} catch (Exception e) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
创建集合
我们可以使用 com.mongodb.client.MongoDatabase 类中的createCollection()来创建集合
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
mongoDatabase.createCollection("test");
System.out.println("集合创建成功");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
获取集合
我们可以使用com.mongodb.client.MongoDatabase类的 getCollection() 方法来获取一个集合
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("集合 test 选择成功");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
插入文档
我们可以使用com.mongodb.client.MongoCollection类的 insertMany() 方法来插入一个文档
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("集合 test 选择成功");
//插入文档
/**
* 1. 创建文档 org.bson.Document 参数为key-value的格式
* 2. 创建文档集合List<Document>
* 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document)
* */
Document document = new Document("title", "MongoDB").
append("description", "database").
append("likes", 100).
append("by", "Fly");
List<Document> documents = new ArrayList<Document>();
documents.add(document);
collection.insertMany(documents);
System.out.println("文档插入成功");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
检索所有文档
我们可以使用 com.mongodb.client.MongoCollection 类中的 find() 方法来获取集合中的所有文档。
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("集合 test 选择成功");
//检索所有文档
/**
* 1. 获取迭代器FindIterable<Document>
* 2. 获取游标MongoCursor<Document>
* 3. 通过游标遍历检索出的文档集合
* */
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
更新文档
你可以使用 com.mongodb.client.MongoCollection 类中的 updateMany() 方法来更新集合中的文档。
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("集合 test 选择成功");
//更新文档 将文档中likes=100的文档修改为likes=200
collection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));
//检索查看结果
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
删除第一个文档
要删除集合中的第一个文档,首先你需要使用com.mongodb.DBCollection类中的 findOne()方法来获取第一个文档,然后使用remove 方法删除。
import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 连接到 mongodb 服务 MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 连接到数据库 MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); MongoCollection<Document> collection = mongoDatabase.getCollection("test"); System.out.println("集合 test 选择成功"); //删除符合条件的第一个文档 collection.deleteOne(Filters.eq("likes", 200)); //删除所有符合条件的文档 collection.deleteMany (Filters.eq("likes", 200)); //检索查看结果 FindIterable<Document> findIterable = collection.find(); MongoCursor<Document> mongoCursor = findIterable.iterator(); while(mongoCursor.hasNext()){ System.out.println(mongoCursor.next()); } }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }