Maven Dependency:

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>

Make a Connection

The following example shows five ways to connect to the database mydb on the local machine. If the database does not exist, MongoDB will create it for you.

// To directly connect to a single MongoDB server, default host is 127.0.0.1 and default port is 27017
// (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");

At this point, the database object will be a connection to a MongoDB server for the specified database.

MongoClient

The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

IMPORTANT

Typically you only create one MongoClient instance for a given database cluster and use it across your application. When creating multiple instances:

  • All resource usage limits (max connections, etc) apply per MongoClient instance
  • To dispose of an instance, make sure you call MongoClient.close() to clean up resources

Get a Collection

To get a collection to operate upon, specify the name of the collection to the getCollection() method. The following example gets the collection test:

MongoCollection<Document> collection = database.getCollection("test");

Insert a Document

Once you have the collection object, you can insert documents into the collection. For example, consider the following JSON document; the document contains a field info which is an embedded document:

{
"name": "MongoDB",
"type": "database",
"count": 1,
"info": {
"x": 203,
"y": 102
}
}

To create the document using the Java driver, use the Document class. You can use this class to create the embedded document as well.

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

Now that we’ve inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the count() method. The following code should print 101.

System.out.println(collection.count());

Query the Collection

Use the find() method to query the collection.

Find the First Document in a Collection

To get the first document in the collection, call the first() method on the find() operation. collection.find().first() returns the first document or null rather than a cursor. This is useful for queries that should only match a single document, or if you are interested in the first document only.

The following example prints the first document found in the collection.

Document myDoc = collection.find().first();
System.out.println(myDoc.toJson());

The example should print the following document:

{ "_id" : { "$oid" : "583c1f1ac18c6ca940773ba3" }, "name" : "MongoDB", "type" : "database", "count" : 1, "info" : { "x" : 203, "y" : 102 } }

NOTE

The _id element has been added automatically by MongoDB to your document and your value will differ from that shown. MongoDB reserves field names that start with “_” and “$” for internal use.

Find All Documents in a Collection

To retrieve all the documents in the collection, we will use the find() method. The find() method returns a FindIterable instance that provides a fluent interface for chaining or controlling find operations. Use the iterator() method to get an iterator over the set of documents that matched the query and iterate. The following code retrieves all documents in the collection and prints them out (101 documents):

MongoCursor<Document> cursor = collection.find().iterator();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}

Although the following idiom is permissible, its use is discouraged as the application can leak a cursor if the loop terminates early:

for (Document cur : collection.find()) {
System.out.println(cur.toJson());
}

Get A Single Document with a Query Filter

We can create a filter to pass to the find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the “i” field is 71, we would do the following:

import static com.mongodb.client.model.Filters.*;

myDoc = collection.find(eq("i", 71)).first();
System.out.println(myDoc.toJson());

and it should just print just one document

{ "_id" : { "$oid" : "583c1f6bc18c6cac30e6cc1b" }, "i" : 71 }

NOTE

Use the Filters, Sorts, Projections and Updates helpers for simple and concise ways of building up queries.

Get a Set of Documents with a Query

We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write:

// now use a range query to get a larger subset
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);

Notice we use the forEach method on FindIterable which applies a block to each document and we print all documents where i > 50.

We could also get a range, say 50 < i <= 100:

collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);

Sorting documents

We can also use the Sorts helpers to sort documents. We add a sort to a find query by calling the sort() method on a FindIterable. Below 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

Sometimes we don’t need all the data contained in a document, the Projections helpers help build the projection parameter for the find operation. Below we’ll sort the collection, exclude the _id field by using the Projections.excludeId and output the first matching document:

myDoc = collection.find().projection(excludeId()).first();
System.out.println(myDoc.toJson());

Aggregations

Sometimes we need to aggregate the data stored in MongoDB. The Aggregates helper provides builders for each of type of aggregation stage.

Below we’ll do a simple two step transformation that will calculate the value of i * 10. First we find all Documents where i > 0 by using the Aggregates.match helper. Then we reshape the document by using Aggregates.project in conjunction with the $multiply operator to calculate the “ITimes10” value:

collection.aggregate(asList(
match(gt("i", 0)),
project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}")))
).forEach(printBlock);

For $group operations use the Accumulators helper for any accumulator operations. Below we sum up all the values of i by using the Aggregates.group helper in conjunction with the Accumulators.sum helper:

myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first();
System.out.println(myDoc.toJson());

NOTE

Currently, there are no helpers for aggregation expressions. Use the Document.parse() helper to quickly build aggregation expressions from extended JSON.

Updating documents

There are numerous update operators supported by MongoDB.

To update at most a single document (may be 0 if none match the filter), use the updateOne method to specify the filter and the update document. Here we use the Updates.set helper to update the first document that meets the filter i equals 10 and set the value of i to 110:

collection.updateOne(eq("i", 10), set("i", 110));

To update all documents matching the filter use the updateMany method. Here we use the Updates.inc helper to increment the value of i by 100 where i is less than 100.

UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100));
System.out.println(updateResult.getModifiedCount());

The update methods return an UpdateResult which provides information about the operation including the number of documents modified by the update.

Deleting documents

To delete at most a single document (may be 0 if none match the filter) use the deleteOne method:

collection.deleteOne(eq("i", 110));

To delete all documents matching the filter use the deleteMany method. Here we delete all documents where i is greater or equal to 100:

DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
System.out.println(deleteResult.getDeletedCount());

The delete methods return a DeleteResult which provides information about the operation including the number of documents deleted.

Bulk operations

These new commands allow for the execution of bulk insert/update/delete operations. There are two types of bulk operations:

  1. Ordered bulk operations.

    Executes all the operation in order and error out on the first write error.

  2. Unordered bulk operations.

    Executes all the operations and reports any the errors.
    Unordered bulk operations do not guarantee order of execution.

Let’s look at two simple examples using ordered and unordered operations:

// 2. Ordered bulk operation - order is guarenteed
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. Unordered bulk operation - no guarantee of order of operation
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));

IMPORTANT

Use of the bulkWrite methods is not recommended when connected to pre-2.6 MongoDB servers, as this was the first server version to support bulk write commands for insert, update, and delete in a way that allows the driver to implement the correct semantics for BulkWriteResult and BulkWriteException. The methods will still work for pre-2.6 servers, but performance will suffer, as each write operation has to be executed one at a time.

Java MongoDB Driver 3.x - Quick Start的更多相关文章

  1. java MongoDB driver error infos

    DataTables warning: table id=dateTable - Ajax error. For more information about this error, please s ...

  2. Java + MongoDB Hello World Example--转载

    原文地址:http://www.mkyong.com/mongodb/java-mongodb-hello-world-example/ A simple Java + MongoDB hello w ...

  3. MongoDB系列:五、MongoDB Driver使用正确的姿势连接复制集

    MongoDB复制集(Replica Set)通过存储多份数据副本来保证数据的高可靠,通过自动的主备切换机制来保证服务的高可用.但需要注意的时,连接副本集的姿势如果不对,服务高可用将不复存在. 使用复 ...

  4. 【MongoDB数据库】Java MongoDB CRUD Example

    上一页告诉我们MongoDB 命令入门初探,本篇blog将基于上一篇blog所建立的数据库和表完毕一个简单的Java MongoDB CRUD Example.利用Java连接MongoDB数据库,并 ...

  5. MongoDB Driver 简单的CURD

    c#中我们可以使用MongoDB.Driver驱动进行对MongoDB数据库的增删改查. 首先需要在NuGet中安装驱动 安装完毕后会发现会有三个引用 其中 MongoDB.Driver和MongoD ...

  6. c# MongoDB Driver 官方教程翻译

    先贴官方文档地址:http://mongodb.github.io/mongo-csharp-driver/2.5/getting_started/quick_tour/ 安装部分很简单,nuget搜 ...

  7. 基于MongoDB.Driver的扩展

    由于MongoDB.Driver中的Find方法也支持表达式写法,结合[通用查询设计思想]这篇文章中的查询思想,个人基于MongoDB扩展了一些常用的方法. 首先我们从常用的查询开始,由于MongoD ...

  8. C# mongoDB Driver 使用对象方式查询语法大全

    #region 查询方法 /// <summary> /// 获取单个对象 /// </summary> /// <typeparam name="T" ...

  9. php MongoDB driver 查询实例

    //是否只查mx $mx_on_switch = I("post.mx_on_switch"); //mx模糊查询 $mx_vague_check = I("post.m ...

随机推荐

  1. HDU 5441 Travel (并查集+数学+计数)

    题意:给你一个带权的无向图,然后q(q≤5000)次询问,问有多少对城市(城市对(u,v)与(v,u)算不同的城市对,而且u≠v)之间的边的长度不超过d(如果城市u到城市v途经城市w, 那么需要城市u ...

  2. HTTP Header 简介

    HTTP Header 简介 HTTP(HyperTextTransferProtocol)即超文本传输协议,目前网页传输的的通用协议.HTTP协议采用了请求/响应模型,浏览器或其他客户端发出请求,服 ...

  3. ie6的兼容问题及解决方案

    1.png24位的图片在ie6浏览器上会出现背景,解决方案是做成png8位: 2.浏览器默认的margin和padding不同,解决方法是用全局重置来统一,即是*{margin:0;padding:0 ...

  4. Exchange模式功能

    Exchange模式: Outlook中的投票功能: 新建邮件--选项--使用投票按钮

  5. Base64 图片转换工具

    以前在写asp的后台的时候,有一个上传功能是必须的,那时候进行的图片预览(未上传前)其实就是获取本地的图片路径来显示图片,但是随着HTML5的出现,可以把图片通过编码来实现预览. 在雅虎的36条速度优 ...

  6. head first c&lt;11&gt;初探网络编程上

    server连接网络四部曲. 为了与外界沟通,c程序用数据流读写字节.比較经常使用的数据流有标准输入.标准输出.文件等. 假设想写一个与网络通信的程序.就须要一种新的数据流----------套接字. ...

  7. MFC Windows程序设计源代码免费下载

    本人近期在网上找到了<MFC Windows程序设计>第二版的书内程序的源代码,特意上传CSDN上面,供学习MFC的程序猿们免费下载. 源代码下载: http://download.csd ...

  8. [Angular 2] *ngFor

    heros.ts: import {Component} from "@angular/core"; const HEROES = [ {id: 1, name:'Superman ...

  9. 配置Log4j(非常具体)

    来自: http://www.blogjava.net/zJun/archive/2006/06/28/55511.html Log4J的配置文件(Configuration File)就是用来设置记 ...

  10. C#多线程的介绍(园子里比较全的一篇)

    一.多线程的概念  Windows是一个多任务的系统,如果你使用的是windows 2000及其以上版本,你可以通过任务管理器查看当前系统运行的程序和进程.什么是进程呢?当一个程序开始运行时,它就是一 ...