【前言】
由于处于线程安全等考虑,MongoDBJava从3.0开始已经打算废弃DB开头的类的使用,所以整体调用上有了较大的区别,特以此文志之
【正文】
环境配置
在Java程序中如果要使用MongoDB,你需要确保已经安装了Java环境及MongoDB JDBC 驱动。
· 首先你必须下载mongo jar包,
Git下载地址:https://github.com/mongodb/mongo-java-driver/downloads,
国内快速下载地址:http://central.maven.org/maven2/org/mongodb/mongo-java-driver/
网盘下载地址:http://pan.baidu.com/s/1i3Mv0dn (这里测试使用3.2.2版)。
· 你需要将mongo.jar包含在你的 classpath中
连接数据库
连接数据库,你需要指定数据库名称,如果指定的数据库不存在,mongo会自动创建数据库。
连接数据库的Java代码如下:
- import java.util.ArrayList;
- import java.util.List;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.MongoDatabase;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
创建集合
我们可以使用com.mongodb.client.MongoDatabase类中的createCollection()来创建集合
代码片段如下:
- import java.util.ArrayList;
- import java.util.List;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.MongoDatabase;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- //创建集合 参数为 “集合名称”
- mongoDatabase.createCollection("collectionName");
- System.out.println("Collection created successfully");
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
获取集合
我们可以使用com.mongodb.DBCollection类的 getCollection()方法来获取一个集合
代码片段如下:
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoDatabase;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- //获取集合 参数为“集合名称”
- MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
- System.out.println("Collection mycol selected successfully");
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
插入文档
我们可以使用com.mongodb.client.MongoCollection类的insert()方法来插入一个文档
代码片段如下:
- import java.util.ArrayList;
- import java.util.List;
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoDatabase;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- //获取集合 参数为“集合名称”
- MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
- System.out.println("Collection mycol selected successfully");
- //插入文档
- /**
- * 1. 创建文档 org.bson.Document 参数为key-value的格式
- * 2. 创建文档集合List<Document>
- * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document)
- * */
- Document document = new Document("title", "MongoDB").
- append("description", "database").
- append("likes", 100).
- append("by", "Fly");
- List<Document> documents = new ArrayList<Document>();
- documents.add(document);
- mongoCollection.insertMany(documents);
- System.out.println("Document inserted successfully");
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
检索所有文档
我们可以使用com.mongodb.client.MongoCollection类中的find()方法来获取集合中的所有文档。
此方法返回一个游标,所以你需要遍历这个游标。
代码片段如下:
- import java.util.ArrayList;
- import java.util.List;
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.FindIterable;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoCursor;
- import com.mongodb.client.MongoDatabase;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- //获取集合 参数为“集合名称”
- MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
- System.out.println("Collection mycol selected successfully");
- //检索所有文档
- /**
- * 1. 获取迭代器FindIterable<Document>
- * 2. 获取游标MongoCursor<Document>
- * 3. 通过游标遍历检索出的文档集合
- * */
- FindIterable<Document> findIterable = mongoCollection.find();
- MongoCursor<Document> mongoCursor = findIterable.iterator();
- while(mongoCursor.hasNext()){
- System.out.println(mongoCursor.next());
- }
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
更新文档
你可以使用com.mongodb.client.MongoCollection类中的 updateOne()或updateMany()方法来更新集合中的文档。
代码片段如下:
- import java.util.ArrayList;
- import java.util.List;
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.FindIterable;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoCursor;
- import com.mongodb.client.MongoDatabase;
- import com.mongodb.client.model.Filters;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("userName", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
- System.out.println("Connect to database successfully");
- //获取集合 参数为“集合名称”
- MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
- System.out.println("Collection mycol selected successfully");
- //更新文档 将文档中likes=100的文档修改为likes=200
- mongoCollection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));
- //检索查看结果
- FindIterable<Document> findIterable = mongoCollection.find();
- MongoCursor<Document> mongoCursor = findIterable.iterator();
- while(mongoCursor.hasNext()){
- System.out.println(mongoCursor.next());
- }
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
删除文档
要删除集合中符合条件的文档,需要使用com.mongodb.client.MongoCollection类中的deleteOne ()或deleteMany()方法。分别表示删除第一个符合条件的文档和删除所有符合条件的文档。
代码片段如下:
- import java.util.ArrayList;
- import java.util.List;
- import org.bson.Document;
- import com.mongodb.MongoClient;
- import com.mongodb.MongoCredential;
- import com.mongodb.ServerAddress;
- import com.mongodb.client.FindIterable;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoCursor;
- import com.mongodb.client.MongoDatabase;
- import com.mongodb.client.model.Filters;
- public class MongoDBJDBC {
- public static void main(String[] args){
- try {
- //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
- //ServerAddress()两个参数分别为 服务器地址 和 端口
- ServerAddress serverAddress = new ServerAddress("localhost",27017);
- List<ServerAddress> addrs = new ArrayList<ServerAddress>();
- addrs.add(serverAddress);
- //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
- MongoCredential credential = MongoCredential.createScramSha1Credential("userName", "databaseName", "password".toCharArray());
- List<MongoCredential> credentials = new ArrayList<MongoCredential>();
- credentials.add(credential);
- //通过连接认证获取MongoDB连接
- MongoClient mongoClient = new MongoClient(addrs,credentials);
- //连接到数据库
- MongoDatabase mongoDatabase = mongoClient.getDatabase("<span style="font-family: Arial, Helvetica, sans-serif;">databaseName</span><span style="font-family: Arial, Helvetica, sans-serif;">");</span>
- System.out.println("Connect to database successfully");
- //获取集合 参数为“集合名称”
- MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
- System.out.println("Collection mycol selected successfully");
- //删除符合条件的第一个文档
- mongoCollection.deleteOne(Filters.eq("likes", 200));
- //删除所有符合条件的文档
- mongoCollection.deleteMany (Filters.eq("likes", 200));
- //检索查看结果
- FindIterable<Document> findIterable = mongoCollection.find();
- MongoCursor<Document> mongoCursor = findIterable.iterator();
- while(mongoCursor.hasNext()){
- System.out.println(mongoCursor.next());
- }
- } catch (Exception e) {
- System.err.println( e.getClass().getName() + ": " + e.getMessage() );
- }
- }
- }
要注意,上面的数据库连接我都没有手动调用关闭,为了防止意外发生建议加上如下代码:
- finally{
- mongoClient.close();
- }
你还可以使用aggregate(),createIndex(),count()等方法来操作MongoDB数据库、集合。