Java MongoDB Driver 3.x - Quickly Start

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.

时间: 2024-08-26 03:09:59

Java MongoDB Driver 3.x - Quickly Start的相关文章

java MongoDB driver error infos

DataTables warning: table id=dateTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7 http://datatables.net/manual/tech-notes/7

那位帮忙提供一个java mongodb多个collection进行mapreduce的操作。

原文:那位帮忙提供一个java mongodb多个collection进行mapreduce的操作. 代码下载地址:http://www.zuidaima.com/share/1550463227890688.htm 我想统计下每个月某个视频的播放量,需要跨日表去mapreduce. 那位帮忙提供一个java mongodb多个collection进行mapreduce的操作.,布布扣,bubuko.com

【MongoDB数据库】Java MongoDB CRUD Example

上一篇我们讲了MongoDB 的命令入门初探,本篇blog将基于上一篇blog所建立的数据库和表完毕一个简单的Java MongoDB CRUD Example,利用Java连接MongoDB数据库.并实现创建数据库.获取表.遍历表中的对象.对表中对象进行CRUD操作等例程. 1.下载MongoDB Java 支持驱动包 [gitHub下载地址]https://github.com/mongodb/mongo-java-driver/downloads 2.建立Javaproject,并导入ja

MongoDB.Driver 2.4以上版本 在.NET中的基本操作

MongoDB.Driver是操作mongo数据库得驱动,最近2.0以下版本已经从GitHub和Nuget中移除了,也就是说.NET Framework4.0不再能从官方获取到MongoDB得驱动了,其次MongoDB.Driver2.0开始API变更巨大,本文不适用MongoDB.Driver2.0以下版本,亦不适用.NET Framework4.5以下版本 要在.NET中使用MongoDB,就必须引用MongoDB的驱动,使用Nuget安装MongoDB.Driver是最方便得,目前Nuge

java MongoDB查询(二)复杂查询

前言 在上篇<java MongoDB查询(一)简单查询>中我们简单了解了下查询,但是仅仅有那些查询是不够用的,还需要复杂的查询,这篇就这点进行叙述. 1.数据结构 集合:firstCollection 数据内容: { "_id" : ObjectId("55adba52fa1f3cf038c2aea6"), "name" : "user0", "age" : 22, "sex&quo

java MongoDB分页优化

最近项目在做网站用户数据新访客统计,数据存储在MongoDB中,统计的数据其实也并不是很大,1000W上下,但是公司只配给我4G内存的电脑,让我程序跑起来气喘吁吁...很是疲惫不堪. 最常见的问题莫过于查询MongoDB内存溢出,没办法只能分页查询.这种思想大家可能都会想到,但是如何分页,确实多有门道! 网上用的最多的,也是最常见的分页采用的是skip+limit这种组合方式,这种方式对付小数据倒也可以,但是对付上几百上千万的大数据,却只能望而兴叹... 经过网上各种查找资料,寻师问道的,发现了

Java MongoDB : Save image example

Java MongoDB : Save image example In this tutorial, we show you how to save an image file into MongoDB, via GridFS API. The GridFS APIs are able to serve other binary files as well, like video and music files. 译:在本教程中,我们将向你展示如何通过 GridFS API 保存一个图片到Mo

MongoDB 3.0 关于安全认证后使用C#调用碰上“System.TimeoutException”类型的异常在 MongoDB.Driver.Core.dll 中发生的相关问题

"System.TimeoutException"类型的异常在 MongoDB.Driver.Core.dll 中发生,但未在用户代码中进行处理 操作MongoDB类库版本: ---------------------------------------------- MongoDB.Driver 2.3 MongoDB.Driver.Core 2.3 MongoDB.Bson 2.3 MongoDB 版本 3.0 连接字符串的相关变化: -----------------------

Mongodb.Driver操作MongoDB

上一篇博客主要介绍了MongoDB和它的的使用场景,这篇文章主要介绍一下如何用C#如何借助官方的Mongodb.Driver操作MongoDB 1.NuGet引入Mongodb.Dirver 安装后项目中会新增如下dll MongoDB.Driver.dll:顾名思义,驱动程序 MongoDB.Bson.dll:序列化.Json相关 2.初始化集合,子类需重写集合名 #region 构造函数 /// <summary> /// 集合 /// </summary> public st