Getting Started with Java Driver
Introduction
This page is a brief overview of working with the MongoDB Java Driver.
For more information about the Java API, please refer to the online API Documentation for Java Driver.
A Quick Tour
Using the Java driver is very simple. First, be sure to include the driver jar mongo.jar in your classpath. The following code snippets come from theexamples/QuickTour.java example code found in the driver.
Making a Connection
To make a connection to a MongoDB, you need to have at the minimum, the name of a database to connect to. The database doesn’t have to exist - if it doesn’t, MongoDB will create it for you.
Additionally, you can specify the server address and port when connecting. The following example shows three ways to connect to the database mydbon the local machine :
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
MongoClient mongoClient = new MongoClient();
// or
MongoClient mongoClient = new MongoClient( "localhost" );
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// or, to connect to a replica set, supply a seed list of members
MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
DB db = mongoClient.getDB( "mydb" );
At this point, the db object will be a connection to a MongoDB server for the specified database. With it, you can do further operations.
Note
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. See the concurrency doc page for more information.
The MongoClient class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given database cluster and use it across your application. If for some reason you decide to create many MongoClient instances, note that:
- 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
New in version 2.10.0: The MongoClient class is new in version 2.10.0. For releases prior to that, please use the Mongo class instead.
Authentication (Optional)
MongoDB can be run in a secure mode where access to databases is controlled through name and password authentication. When run in this mode, any client application must provide a name and password before doing any operations. In the Java driver, you simply do the following with aMongoClient instance:
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");
boolean auth = db.authenticate(myUserName, myPassword);
If the name and password are valid for the database, auth will be true. Otherwise, it will be false. You should look at the MongoDB log for further information if available.
Most users run MongoDB without authentication in a trusted environment.
Getting a List Of Collections
Each database has zero or more collections. You can retrieve a list of them from the db (and print out any that are there) :
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
System.out.println(s);
}
and assuming that there are two collections, name and address, in the database, you would see
name
address
as the output.
Getting a Collection
To get a collection to use, just specify the name of the collection to the getCollection(String collectionName) method:
DBCollection coll = db.getCollection("testCollection");
Once you have this collection object, you can now do things like insert data, query for data, etc
Setting Write Concern
As of version 2.10.0, the default write concern is WriteConcern.ACKNOWLEDGED, but it can be easily changed:
mongoClient.setWriteConcern(WriteConcern.JOURNALED);
There are many options for write concern. Additionally, the default write concern can be overridden on the database, collection, and individual update operations. Please consult the API Documentation for details.
Changed in version 2.10.0: Prior to version 2.10.0, the default write concern is WriteConcern.NORMAL. Under normal circumstances, clients will typically change this to ensure they are notified of problems writing to the database.
Inserting a Document
Once you have the collection object, you can insert documents into the collection. For example, lets make a little document that in JSON would be represented as
{
"name" : "MongoDB",
"type" : "database",
"count" : 1,
"info" : {
x : 203,
y : 102
}
}
Notice that the above has an “inner” document embedded within it. To do this, we can use the BasicDBObject class to create the document (including the inner document), and then just simply insert it into the collection using the insert() method.
BasicDBObject doc = new BasicDBObject("name", "MongoDB").
append("type", "database").
append("count", 1).
append("info", new BasicDBObject("x", 203).append("y", 102));
coll.insert(doc);
Finding the First Document in a Collection Using findOne()
To show that the document we inserted in the previous step is there, we can do a simple findOne() operation to get the first document in the collection. This method returns a single document (rather than the DBCursor that the find() operation returns), and it’s useful for things where there only is one document, or you are only interested in the first. You don’t have to deal with the cursor.
DBObject myDoc = coll.findOne();
System.out.println(myDoc);
and you should see
{ "_id" : "49902cde5162504500b45c2c" ,
"name" : "MongoDB" ,
"type" : "database" ,
"count" : 1 ,
"info" : { "x" : 203 , "y" : 102}}
Note
The _id element has been added automatically by MongoDB to your document. Remember, MongoDB reserves element names that start with “_”/”$” for internal use.
Adding Multiple Documents
In order to do more interesting things with queries, let’s add multiple simple documents to the collection. These documents will just be
{
"i" : value
}
and we can do this fairly efficiently in a loop
for (int i=0; i < 100; i++) {
coll.insert(new BasicDBObject("i", i));
}
Notice that we can insert documents of different “shapes” into the same collection. This aspect is what we mean when we say that MongoDB is “schema-free”
Counting 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 thegetCount() method.
System.out.println(coll.getCount());
and it should print 101.
Using a Cursor to Get All the Documents
In order to get all the documents in the collection, we will use the find() method. The find() method returns a DBCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out :
DBCursor cursor = coll.find();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
and that should print all 101 documents in the collection.
Getting A Single Document with A Query
We can create a query 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 ;
BasicDBObject query = new BasicDBObject("i", 71);
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
and it should just print just one document
{ "_id" : "49903677516250c1008d624e" , "i" : 71 }
You may commonly see examples and documentation in MongoDB which use $ Operators, such as this:
db.things.find({j: {$ne: 3}, k: {$gt: 10} });
These are represented as regular String keys in the Java driver, using embedded DBObjects:
BasicDBObject query = new BasicDBObject("j", new BasicDBObject("$ne", 3).
append("k", new BasicDBObject("$gt", 10));
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
Getting 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 :
query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // e.g. find all where i > 50
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
which should print the documents where i > 50.
We could also get a range, say 20 < i <= 30:
query = new BasicDBObject("i", new BasicDBObject("$gt", 20).
append("$lte", 30)); // i.e. 20 < i <= 30
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
Quick Tour of the Administrative Functions
Creating An Index
MongoDB supports indexes, and they are very easy to add on a collection. To create an index, you just specify the field that should be indexed, and specify if you want the index to be ascending (1) or descending (-1). The following creates an ascending index on the i field :
coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending
Getting a List of Indexes on a Collection
You can get a list of the indexes on a collection:
List<DBObject> list = coll.getIndexInfo();
for (DBObject o : list) {
System.out.println(o);
}
and you should see something like
{ "name" : "i_1" , "ns" : "mydb.testCollection" , "key" : { "i" : 1} }
Getting A List of Databases
You can get a list of the available databases:
MongoClient mongoClient = new MongoClient();
for (String s : m.getDatabaseNames()) {
System.out.println(s);
}
Dropping A Database
You can drop a database by name using a MongoClient instance:
MongoClient mongoClient = new MongoClient();
mongoClient.dropDatabase("myDatabase");
相关推荐
MongoDB的Java驱动程序是连接Java应用程序与MongoDB服务器的关键组件,它提供了丰富的API来执行各种数据库操作。在本篇文章中,我们将深入探讨`mongodb-driver-core-3.5.0.jar`这一核心驱动包及其相关组件。 `...
MongoDB异步驱动程序(mongodb-async-driver)是为Java开发者设计的一个库,它允许应用程序以非阻塞的方式与MongoDB服务器进行通信,提高了处理大量并发请求的能力。 在"mongodb-async-driver-2.0.1.jar"这个特定...
在Java开发中,与MongoDB的交互通常通过Java驱动程序实现,它提供了对数据库的基本CURD(创建、读取、更新、删除)操作的支持。本篇文章将深入探讨MongoDB在Java环境下的CURD操作,帮助初学者更好地理解和应用。 ...
这些JAR文件是MongoDB Java驱动程序的一部分,允许Java应用程序通过Java Database Connectivity (JDBC)或者原生的MongoDB驱动API来操作MongoDB数据库。 1. `bson-3.9.1.jar`: BSON(Binary JSON)是MongoDB用于存储...
驱动程序支持连接管理、查询构建、数据序列化和异步操作等功能,使得Java应用能够无缝地存取MongoDB数据库。 总结来说,MongoDB是一个强大的NoSQL数据库,MongoDB Compass是其配套的可视化工具,而这个压缩包则提供...
对于"mongodb-windows-x86_64-4.4.6-signed.msi"这个文件,它是Windows安装程序包,用于在Windows操作系统上部署MongoDB。用户只需解压下载的zip文件,然后运行msi安装程序,按照向导的步骤进行安装。安装过程中,你...
安装完成后,用户可以利用MongoDB的命令行工具`mongo`进行数据库管理,创建数据库、集合,执行查询、更新、插入和删除操作。此外,还可以通过`mongodump`和`mongorestore`进行数据备份与恢复,确保数据的安全。 ...
mongo-java-driver-3.4.3.jar 是 MongoDB 官方为 Java 开发者提供的 Java 驱动程序的一...这个 JAR 文件包含了与 MongoDB 数据库进行交互所需的类和接口,允许 Java 应用程序连接到 MongoDB 实例并执行各种数据库操作。
使用java 操作mongoDB必须的jar包,
Java驱动程序是MongoDB官方支持的与Java应用程序进行交互的接口,用于执行CRUD(创建、读取、更新、删除)操作以及其他数据库管理任务。 "mongodb-driver-3.8.0" 是MongoDB Java驱动程序的一个版本,它为Java开发者...
MongoDB Java驱动程序是官方提供的Java API,允许开发者在Java应用中无缝地操作MongoDB数据库。版本3.9.1是一个稳定版本,提供了对MongoDB服务器多个版本的支持,包括错误处理、性能优化以及对新特性的集成。 首先...
MongoDB Java驱动是Java开发者与MongoDB数据库进行交互的重要工具,它允许程序通过Java代码执行CRUD(创建、读取、更新、删除)操作。在本压缩包中,包含了三个核心的jar包以及一个名为`MongoDBJDBC.java`的Java测试...
总的来说,MongoDB异步驱动程序2.0.1版对于那些需要对MongoDB进行异步操作或者使用YCSB进行压测的开发者来说,可能是必需的。尽管它已被废弃,但在某些特定场景下,它仍具有一定的实用价值。在使用过程中,务必注意...
MongoDB Java驱动是Java开发者与MongoDB数据库交互的重要工具,它允许Java应用程序通过标准的Java API来执行查询、插入、更新和删除等操作。在Java中使用MongoDB,首先需要安装并配置对应的驱动版本,以确保与正在...
它支持多种编程语言,如JavaScript、Python、Java、C++等,使得开发人员能够灵活地选择合适的工具进行数据操作。MongoDB 的主要特性包括分布式架构、动态查询、丰富的文档结构以及强大的索引机制。 在Ubuntu 16.04...
MongoDB 是一个面向文档存储的数据库,操作起来比较简单和容易。 你可以在MongoDB记录中设置任何属性的索引 (如:FirstName="Sameer",Address="8 Gandhi Road")来实现更快的排序。 你可以通过本地或者网络创建数据...
你可以通过`mongo`命令行客户端连接到MongoDB服务器,进行数据操作: ```bash mongo ``` 在MongoDB中,数据以文档的形式存储在集合(collection)中,集合类似于关系数据库中的表。每个文档都是一个JSON格式的对象...
了解这些核心概念后,开发者可以更有效地使用MongoDB Java Driver进行数据库操作。在实际项目中,结合Maven或Gradle的配置,将源码依赖库存储在本地不仅可以避免网络问题,还可以加速构建过程,提高开发效率。同时,...
8. **API支持**:MongoDB有多种编程语言的驱动程序,如Python、Java、Node.js等,方便开发者进行集成。 9. **云服务**:MongoDB还提供了MongoDB Atlas,一个完全托管的云数据库服务,用户无需关心基础设施维护。 ...
1. **mongodb-driver-3.6.0.jar**:这是MongoDB Java驱动程序的主要组件,它包含了连接MongoDB服务器、执行查询、更新和插入操作等所需的所有类和接口。3.6.0版本是这个驱动的一个特定版本,确保了与MongoDB 3.6版本...