【引言】
毕竟现在MongoDB还是出于成长阶段,所以现在网上相关的资料很少,而且大部分还都是针对于MongoDB的老版本的。再加上MongoDB的频繁升级、重大更新等等,导致菜鸟学习的难度增大。
好了,前几篇讲的都是MongoDB数据库相关的知识,最终,还是要与java来接轨(当然,卤煮是搞java开发的)。看了看现在的java驱动版本截至目前2016年8月27日为止为3.3,与网上搜索到的教程很多写法不一致,所以卤煮在此决定研究一下官网的教程,希望能对自己或者其他人有一点帮助,足矣...
ps:本文只是官网的一个快速入门,让我这样的菜鸟能了解个大概,有些地方可能还需要深入的学习才能读懂。本人水平有限,有些地方有删减,翻译不到位的地方还请各位看官海涵并留言指出,本人一定虚心学习改正,以免误导!
O shit!突然想起来,MongoDB的java驱动也不好找,忘了给大家提供干货了,特地快马加鞭的补上:mongo-java-driver-3.3.0.jar下载
【翻译篇】
官网原文地址:戳这里
MongoDB驱动程序快速入门
1.创建一个连接
// 简单直接的连接数据库,默认为本机地址localhost,端口号27017
MongoClient mongoClient = new MongoClient();
// 或者像这样指定连接地址
MongoClient mongoClient = new MongoClient( "localhost" );
// 或者像这样指定连接地址和端口号
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 或者像这样连接到一个副本集,需要提供一个列表
MongoClient mongoClient = new MongoClient(
Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
// 或者使用连接字符串
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019");
MongoClient mongoClient = new MongoClient(connectionString);
// 获取到数据库对象mydb,如果不存在则自动创建
MongoDatabase database = mongoClient.getDatabase("mydb");
注意
通常,对于一个数据库集群你仅仅只需要创建一个MongoClient实例,并且使用它来贯穿你的整个应用程序。当创建多个实例的时候:
- 注意每个MongoClient实例的所有资源使用限制(最大连接数等等)
- 销毁实例,请确保你调用
MongoClient.close()
来清理资源
2.获取一个集合
MongoCollection<Document> collection = database.getCollection("test");
3.插入一个文档
{
"name" : "MongoDB",
"type" : "database",
"count" : 1,
"info" : {
x : 203,
y : 102
}
}
Document doc = new Document("name", "MongoDB")
.append("type", "database")
.append("count", 1)
.append("info", new Document("x", 203).append("y", 102));
collection.insertOne(doc);
4.插入多个文档
你可以使用insertMany()方法来插入多个文档。{ "i" : value }
在一个循环中创建文档:
List<Document> documents = new ArrayList<Document>();
for (int i = 0; i < 100; i++) {
documents.add(new Document("i", i));
}
把这些文档插入到集合中,把这个文档列表传递给insertMany()方法:
collection.insertMany(documents);
5.统计集合中的文档数量
System.out.println(collection.count());
6.查询集合
6.1查询集合中的第一个文档
Document myDoc = collection.find().first();
System.out.println(myDoc.toJson());
这个例子将会输出以下内容:
{ "_id" : { "$oid" : "551582c558c7b4fbacf16735" },
"name" : "MongoDB", "type" : "database", "count" : 1,
"info" : { "x" : 203, "y" : 102 } }
注意
_id字段
是由MongoDB自动添加到文档中的,从而与其他的文档进行区分展示。MongoDB保留所有以“_”、“$”为开始的字段名,以供内部使用。
6.2查询集合中的所有文档
MongoCursor<Document> cursor = collection.find().iterator();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
虽然下面的语句是允许的,但是不鼓励使用,因为如果循环提前终止的话可能会遗漏一个游标。
for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}
7.使用查询过滤器得到一个单一的文档
import static com.mongodb.client.model.Filters.*;
myDoc = collection.find(eq("i", 71)).first();
System.out.println(myDoc.toJson());
{ "_id" : { "$oid" : "5515836e58c7b4fbc756320b" }, "i" : 71 }
注意
可以使用 Filters
, Sorts
, Projections
和Updates类来创建简单明了的查询方式。
8.查询一组文档
// 现在使用范围查询来得到一个大点的子集
Block<Document> printBlock = new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
collection.find(gt("i", 50)).forEach(printBlock);
请注意,在这里我们在FindIterable 上面使用了forEach()方法,并且打印出了所有 i>50的文档。
collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);
9.排序
myDoc = collection.find(exists("i")).sort(descending("i")).first();
System.out.println(myDoc.toJson());
exists():查询含有指定字段的文档
10.字段投影
myDoc = collection.find().projection(excludeId()).first();
System.out.println(myDoc.toJson());
11.聚合
collection.aggregate(asList(
match(gt("i", 0)),
project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}")))
).forEach(printBlock);
12.更新文档
collection.updateOne(eq("i", 10), set("i", 110));
要更新所有匹配过滤器的文档,需要使用updateMany()方法。这里我们使用Updates.inc()方法来对i<100的文档进行增加100(即i+100):
UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100));
System.out.println(updateResult.getModifiedCount());
更新方法返回一个UpdateResult对象,该对象提供了包括更新文档的数量等信息。
13.删除文档
<span style="font-size:18px;">collection.deleteOne(eq("i", 110));</span>
使用deleteMany()方法来删除匹配过滤的所有文档。
DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
System.out.println(deleteResult.getDeletedCount());
删除方法返回一个DeleteResult对象,该对象中提供了包括删除文档数量等信息。
14.批量操作

-
有序批量操作。
执行所有预定操作,当出现写入错误时会停止操作。
-
无序批量操作。
执行所有操作,并报告所有的错误。
无序批量操作不保证所有操作的执行。
// 2. 有序批量操作,调用是有保证的
collection.bulkWrite(
Arrays.asList(new InsertOneModel<>(new Document("_id", 4)),
new InsertOneModel<>(new Document("_id", 5)),
new InsertOneModel<>(new Document("_id", 6)),
new UpdateOneModel<>(new Document("_id", 1),
new Document("$set", new Document("x", 2))),
new DeleteOneModel<>(new Document("_id", 2)),
new ReplaceOneModel<>(new Document("_id", 3),
new Document("_id", 3).append("x", 4))));
// 2. 无序批量操作,调用没有保证
collection.bulkWrite(
Arrays.asList(new InsertOneModel<>(new Document("_id", 4)),
new InsertOneModel<>(new Document("_id", 5)),
new InsertOneModel<>(new Document("_id", 6)),
new UpdateOneModel<>(new Document("_id", 1),
new Document("$set", new Document("x", 2))),
new DeleteOneModel<>(new Document("_id", 2)),
new ReplaceOneModel<>(new Document("_id", 3),
new Document("_id", 3).append("x", 4))),
new BulkWriteOptions().ordered(false));
重要
当MongoDB的服务器版本为2.6以下时,不推荐使用bulkWrite方法,因为这是第一个支持批量插入、更新、删除命令的服务器版本,在某种程度上,可以让驱动程序实现BulkWriteResult和BulkWriteException的正确的语义。该方法仍然会在2.6以下版本的服务器工作,但性能将受到影响,因为每个写操作将会被单独执行一次。