MongoDB Java

在本章中,我们将学习如何设置 MongoDB CLIENT。

安装

在 Java 程序中如果要使用 MongoDB,你需要确保已经安装了 Java 环境及 MongoDB JDBC 驱动。

本章节实例适合 Mongo 3.x 以上版本。

你可以参考本站的Java教程来安装Java程序。现在让我们来检测你是否安装了 MongoDB JDBC 驱动。

首先你必须下载mongo jar包,下载地址:https://mongodb.github.io/mongo-java-driver/, 请确保下载最新版本。

downlaod-mongo-java

你需要将 mongo-java-driver-3.2.2.jar (找到合适的版本)包含在你的 classpath 中。

国内 mongodb-driver jar 下载地址:http://central.maven.org/maven2/org/mongodb/mongo-java-driver/


连接到数据库

要连接数据库,您需要指定数据库名称,如果该数据库不存在,则 MongoDB 会自动创建它。

以下是连接到数据库的代码片段

import com.mongodb.client.MongoDatabase; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class ConnectToDB { 
   
   public static void main( String args[] ) {  
      
      // 创建一个客户端链接
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
   
      // 创建认证
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // 访问数据库
      MongoDatabase database = mongo.getDatabase("myDb"); 
      System.out.println("Credentials ::"+ credential);     
   } 
}

现在,让我们编译并运行上面的程序来创建我们的数据库 myDb,如下所示。

$javac ConnectToDB.java 
$java ConnectToDB

执行时,上述程序将输出如下内容。

Connected to the database successfully 
Credentials ::MongoCredential{
   mechanism = null, 
   userName = 'sampleUser', 
   source = 'myDb', 
   password = <hidden>, 
   mechanismProperties = {}
}

创建集合

要创建集合,请使用com.mongodb.client.MongoDatabase类的createCollection()方法。

以下是创建集合的代码片段:

import com.mongodb.client.MongoDatabase; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class CreatingCollection { 
   
   public static void main( String args[] ) {  
      
      // 创建客户端链接
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
     
      // 创建认证
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      //访问数据库
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      //创建集合
      database.createCollection("sampleCollection"); 
      System.out.println("Collection created successfully"); 
   } 
} 

在编译时,上面的程序输出如下结果:

Connected to the database successfully 
Collection created successfully

获取/选择一个集合

要从数据库中获取/选择集合,请使用com.mongodb.client.MongoDatabase类的getCollection()方法。

以下是获取/选择集合的程序

import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoDatabase; 
import org.bson.Document; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class selectingCollection { 
   
   public static void main( String args[] ) {  
      
      // 创建Mongo 客户端链接
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
     
      // 创建认证
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // 访问数据库
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      // 创建一个集合
      System.out.println("Collection created successfully"); 
      // 检索集合
      MongoCollection<Document> collection = database.getCollection("myCollection"); 
      System.out.println("Collection myCollection selected successfully"); 
   }
}

在编译时,上面的程序给你以下结果 -

Connected to the database successfully 
Collection created successfully 
Collection myCollection selected successfully

插入文档

要将文档插入 MongoDB,使用com.mongodb.client.MongoCollection类的insert()方法。

以下是插入文档的代码片段

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
public class InsertingDocument {
    public static void main( String args[] ) {
    
    // 创建一个Mongo 客户端链接
    MongoClient mongo = new MongoClient( "localhost" , 27017 );
    
    // 访问数据库
    MongoDatabase database = mongo.getDatabase("myDb");
    
    // 创建集合
    database.createCollection("sampleCollection");
    System.out.println("Collection created successfully");
    
    // 检索集合
    MongoCollection<Document> collection = database.getCollection("sampleCollection");
    System.out.println("Collection sampleCollection selected successfully");
    Document document = new Document("title", "MongoDB")
    .append("description", "database")
    .append("likes", 100)
    .append("url", "http://www.tutorialspoint.com/mongodb/")
    .append("by", "tutorials point");
    
    //在集合中插入文档
    collection.insertOne(document);
    System.out.println("Document inserted successfully");
}

在编译时,上面的程序输出以下结果:

Connected to the database successfully 
Collection sampleCollection selected successfully 
Document inserted successfully

检索所有文件

要从集合中选择所有文档,请使用com.mongodb.client.MongoCollection类的find()方法。此方法返回一个游标,因此我们需要迭代此游标。

以下是选择所有文件的程序

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class RetrievingAllDocuments {
    public static void main( String args[] ) {
    
        // 创建客户端链接
        MongoClient mongo = new MongoClient( "localhost" , 27017 );
        
        // 认证
        MongoCredential credential;
        credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());
        System.out.println("Connected to the database successfully");
        
        // 访问数据库
        MongoDatabase database = mongo.getDatabase("myDb");
        
        // 检索集合
        MongoCollection<Document> collection = database.getCollection("sampleCollection");
        System.out.println("Collection sampleCollection selected successfully");
        Document document1 = new Document("title", "MongoDB")
        .append("description", "database")
        .append("likes", 100)
        .append("url", "http://www.jiyik.com/w/mongodb/")
        .append("by", "JIYIK");
        Document document2 = new Document("title", "RethinkDB")
        .append("description", "database")
        .append("likes", 200)
        .append("url", "http://www.jiyik.com/rethinkdb/")
        .append("by", "JIYIK");
        List<Document> list = new ArrayList<Document>();
        list.add(document1);
        list.add(document2);
        collection.insertMany(list);
        // 获取迭代对象
        FindIterable<Document> iterDoc = collection.find();
        int i = 1;
        // 获取游标
        Iterator it = iterDoc.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
            i++;
        }
    }
}

在编译时,上面的程序输出以下结果 -

Connected to the database successfully
Collection sampleCollection selected successfully
Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.jiyik.com/w/mongodb/, by=JIYIK}}
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.jiyik.com/rethinkdb/, by=JIYIK}}

更新文件

要从集合中更新文档,请使用com.mongodb.client.MongoCollection类的updateOne()方法。

以下是选择第一个文档的程序

import com.mongodb.client.FindIterable; 
import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoDatabase; 
import com.mongodb.client.model.Filters; 
import com.mongodb.client.model.Updates; 
import java.util.Iterator; 
import org.bson.Document;  
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class UpdatingDocuments { 
   
   public static void main( String args[] ) {  
      
      // 创建客户端链接
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
     
      // 认证
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // 访问数据库
      MongoDatabase database = mongo.getDatabase("myDb"); 
      // 检索集合
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      System.out.println("Collection myCollection selected successfully"); 
      collection.updateOne(Filters.eq("title", 1), Updates.set("likes", 150));       
      System.out.println("Document update successfully...");  
      
      // 更新之后获取文档 
      // 获取迭代对象
      FindIterable<Document> iterDoc = collection.find(); 
      int i = 1; 
      // 获取游标
      Iterator it = iterDoc.iterator(); 
      while (it.hasNext()) {  
         System.out.println(it.next());  
         i++; 
      }     
   }  
}

在编译时,上面的程序输出以下结果 -

Connected to the database successfully
Collection myCollection selected successfully
Document update successfully...
Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.jiyik.com/w/mongodb/, by=JIYIK}}
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.jiyik.com/rethinkdb/, by=JIYIK}}

删除文档

要从集合中删除文档,需要使用com.mongodb.client.MongoCollection类的deleteOne()方法。

以下是删除文档的程序

import com.mongodb.client.FindIterable; 
import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoDatabase; 
import com.mongodb.client.model.Filters;  
import java.util.Iterator; 
import org.bson.Document; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class DeletingDocuments { 
   
   public static void main( String args[] ) {  
   
      // 创建客户端链接
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      
      // 认证
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // 访问数据库
      MongoDatabase database = mongo.getDatabase("myDb"); 
      // 检索集合
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      System.out.println("Collection sampleCollection selected successfully"); 
      // 删除对象
      collection.deleteOne(Filters.eq("title", "MongoDB")); 
      System.out.println("Document deleted successfully...");  
      
      // 更新之后获取文档 
      // 获取迭代对象
      FindIterable<Document> iterDoc = collection.find(); 
      int i = 1; 
      // 获取游标
      Iterator it = iterDoc.iterator(); 
      while (it.hasNext()) {  
         System.out.println(it.next());  
         i++; 
      }       
   } 
}

在编译时,上面的程序输出以下结果 -

Connected to the database successfully 
Collection sampleCollection selected successfully 
Document deleted successfully...
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.jiyik.com/rethinkdb/, by=JIYIK}}

删除集合

要从数据库中删除集合,你需要使用com.mongodb.client.MongoCollection类的drop()方法。

以下是删除集合的程序

import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoDatabase;  
import org.bson.Document;  
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class DropingCollection { 
   
   public static void main( String args[] ) {  
      // 创建客户端链接
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
      // 认证
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // 访问数九
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      // 创建集合
      System.out.println("Collections created successfully"); 
      // 检索集合
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      // 删除集合
      collection.drop(); 
      System.out.println("Collection dropped successfully");
   } 
}

在编译时,上面的程序输出以下结果 -

Connected to the database successfully 
Collection sampleCollection selected successfully 
Collection dropped successfully

列出所有集合

要列出数据库中的所有集合,你需要使用com.mongodb.client.MongoDatabase类的listCollectionNames() 方法。

以下是列出数据库所有集合的程序

import com.mongodb.client.MongoDatabase; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class ListOfCollection { 
   
   public static void main( String args[] ) {  
      
      // 创建链接
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
      // 认证
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // 访问数据库
      MongoDatabase database = mongo.getDatabase("myDb"); 
      System.out.println("Collection created successfully"); 
      for (String name : database.listCollectionNames()) { 
         System.out.println(name); 
      } 
   }
} 

在编译时,上面的程序输出以下结果 -

Connected to the database successfully 
Collection created successfully 
myCollection 
myCollection1 
myCollection5

其余的 MongoDB 方法save()、limit()、skip()、sort()等的工作方式与后续教程中的解释相同。

查看笔记

扫码一下
查看教程更方便