MongoDB Java CRUD 示例教程
欢迎来到 MongoDB Java 示例教程。之前我们学习了如何在 Unix 机器上安装 MongoDB以及如何从终端执行一些命令。今天我们将研究MongoDB Java驱动程序功能以及如何执行常见的 CRUD(创建、读取、更新、删除)操作。
MongoDB Java
-
MongoDB Java 驱动程序下载
如果您有 maven 项目,只需添加以下依赖项即可将 MongoDB java 驱动程序包含到您的应用程序中。
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.12.3</version> </dependency>
如果您有一个独立项目,您可以从此链接下载 MongoDB Java 驱动程序并将其包含在您的项目构建路径中。现在让我们了解一下 MongoDB Java 驱动程序的一些基本用法,然后我们将研究MongoDB Java 示例程序的 CRUD 操作。
-
创建 MongoDB Java 连接
MongoClient是我们的 Java 程序和 MongoDB 服务器之间的接口。
MongoClient
用于创建连接、连接到数据库、检索集合名称以及创建/读取/更新/删除数据库、集合、文档等。我最喜欢的 MongoDB Java 驱动程序功能之一是它是线程安全的,因此我们可以创建MongoClient
一次实例并重复使用它。即使多个线程同时访问它,也会从它维护的内部连接池中返回一个连接。对于对数据库的每个请求(查找、插入等),Java 线程都将从池中获取一个连接,执行操作并释放连接。这意味着每次使用的连接(套接字)可能不同。以下是连接到 MongoDB 服务器的一些常用方法。MongoClient mongoClient = new MongoClient(); //connects to default host and port i.e 127.0.0.1:27017 // or MongoClient mongoClient = new MongoClient( "localhost" ); //connects to default port i.e 27017 // or MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // should use this always // or, to connect to a replica set, with auto-discovery of the primary MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017), new ServerAddress("localhost", 27018), new ServerAddress("localhost", 27019)));
-
连接到 MongoDB 数据库
一旦我们连接到 MongoDB 服务器,下一步就是创建与数据库的连接,如下所示。请注意,如果数据库不存在,MongoDB 将为您创建它。
MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("journaldev");
MongoClient 提供了一个有用的方法来获取所有数据库名称,如下所示。
MongoClient mongo = new MongoClient("localhost", 27017); List<String> dbs = mongo.getDatabaseNames(); System.out.println(dbs); // [journaldev, local, admin]
我们可以对数据库进行基于用户密码的身份验证,在这种情况下,我们需要提供如下所示的授权凭证。
MongoCredential journaldevAuth = MongoCredential.createPlainCredential("pankaj", "journaldev", "pankaj123".toCharArray()); MongoCredential testAuth = MongoCredential.createPlainCredential("pankaj", "test", "pankaj123".toCharArray()); List<MongoCredential> auths = new ArrayList<MongoCredential>(); auths.add(journaldevAuth); auths.add(testAuth); ServerAddress serverAddress = new ServerAddress("localhost", 27017); MongoClient mongo = new MongoClient(serverAddress, auths);
如果您使用的是旧版本,则需要在获取数据库对象后提供身份验证详细信息,如下所示。
MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("journaldev"); boolean auth = db.authenticate("pankaj", "pankaj123".toCharArray());
您可以轻松找出早期方法中的缺陷,身份验证应在早期阶段完成,因为我们无法从中恢复。我们可以通过使用
MongoClient
dropDatabase(String db)
方法或DB
dropDatabase()
方法删除数据库。由于我们要删除数据库,我更喜欢使用 MongoClient 方法。 -
MongoDB 和集合
每个数据库都可以有零个或多个集合,它们就像关系数据库服务器中的表,只是您没有特定的数据格式。就 Java 编程语言而言,可以将其视为通用列表与字符串列表。我们可以使用以下代码获取所有集合名称。
MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("journaldev"); Set<String> collections = db.getCollectionNames(); System.out.println(collections); // [datas, names, system.indexes, users]
我们可以通过提供其名称来获取特定的集合,如下所示。
DB db = mongo.getDB("journaldev"); DBCollection col = db.getCollection("users");
同样,如果集合不存在,MongoDB 将为您创建它。MongoDB 中的所有数据都放入某个集合中,因此此时我们已准备好执行插入/更新/删除操作。我们可以使用
DBCollection
drop()
方法从数据库中删除集合。 -
MongoDB Java 示例
Even though we can work on any valid JSON document in MongoDB collection, in real life we have POJO classes that are mapped with these data. So I will create a java bean and use it for my examples. `User.java`
```
package com.journaldev.mongodb.model;
public class User {
private int id;
private String name;
private String role;
private boolean isEmployee;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public boolean isEmployee() {
return isEmployee;
}
public void setEmployee(boolean isEmployee) {
this.isEmployee = isEmployee;
}
}
```
Here is the complete MongoDB java example program showing all the CRUD operations one by one. `MongoDBExample.java`
```
package com.journaldev.mongodb.main;
import java.net.UnknownHostException;
import com.journaldev.mongodb.model.User;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteResult;
public class MongoDBExample {
public static void main(String[] args) throws UnknownHostException {
User user = createUser();
DBObject doc = createDBObject(user);
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("journaldev");
DBCollection col = db.getCollection("users");
//create user
WriteResult result = col.insert(doc);
System.out.println(result.getUpsertedId());
System.out.println(result.getN());
System.out.println(result.isUpdateOfExisting());
System.out.println(result.getLastConcern());
//read example
DBObject query = BasicDBObjectBuilder.start().add("_id", user.getId()).get();
DBCursor cursor = col.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
//update example
user.setName("Pankaj Kumar");
doc = createDBObject(user);
result = col.update(query, doc);
System.out.println(result.getUpsertedId());
System.out.println(result.getN());
System.out.println(result.isUpdateOfExisting());
System.out.println(result.getLastConcern());
//delete example
result = col.remove(query);
System.out.println(result.getUpsertedId());
System.out.println(result.getN());
System.out.println(result.isUpdateOfExisting());
System.out.println(result.getLastConcern());
//close resources
mongo.close();
}
private static DBObject createDBObject(User user) {
BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();
docBuilder.append("_id", user.getId());
docBuilder.append("name", user.getName());
docBuilder.append("role", user.getRole());
docBuilder.append("isEmployee", user.isEmployee());
return docBuilder.get();
}
private static User createUser() {
User u = new User();
u.setId(2);
u.setName("Pankaj");
u.setEmployee(true);
u.setRole("CEO");
return u;
}
}
```
A sample execution results in following output.
```
null
0
false
WriteConcern { "getlasterror" : 1} / (Continue on error? false)
{ "_id" : 2 , "name" : "Pankaj" , "role" : "CEO" , "isEmployee" : true}
null
1
true
WriteConcern { "getlasterror" : 1} / (Continue on error? false)
null
1
false
WriteConcern { "getlasterror" : 1} / (Continue on error? false)
```
Notice that I am saving User id with **\_id** name, this is a reserved key for the primary key of any record in the collection. If we don't provide one, MongoDB will create one for us. It's like sequencer or auto increment column in relational database tables. Since I am deleting the created record, further execution won't cause any issues. But if there are duplicate record, then we will get below errors.
```
Exception in thread "main" com.mongodb.MongoException$DuplicateKey: { "serverUsed" : "localhost:27017" , "ok" : 1 , "n" : 0 ,
"err" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: journaldev.users.$_id_ dup key: { : 1 }" ,
"code" : 11000}
at com.mongodb.CommandResult.getWriteException(CommandResult.java:88)
at com.mongodb.CommandResult.getException(CommandResult.java:79)
at com.mongodb.DBCollectionImpl.translateBulkWriteException(DBCollectionImpl.java:314)
at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:189)
at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:165)
at com.mongodb.DBCollection.insert(DBCollection.java:93)
at com.mongodb.DBCollection.insert(DBCollection.java:78)
at com.mongodb.DBCollection.insert(DBCollection.java:120)
at com.journaldev.mongodb.main.MongoDBExample.main(MongoDBExample.java:27)
```
这就是您开始使用 MongoDB Java 驱动程序的全部内容,我们将在下一篇文章中介绍更多功能。