教程 > mongodb 教程 > 阅读:24

mongodb java——迹忆客-ag捕鱼王app官网

在本章中,我们将学习如何设置 mongodb client。

安装

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

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

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

首先你必须下载mongo jar包,下载地址:, 请确保下载最新版本。

downlaod-mongo-java

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

国内 mongodb-driver jar 下载地址:


连接到数据库

要连接数据库,您需要指定数据库名称,如果该数据库不存在,则 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 = , 
   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 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 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 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 list = new arraylist();
        list.add(document1);
        list.add(document2);
        collection.insertmany(list);
        // 获取迭代对象
        finditerable 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 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 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 collection = database.getcollection("samplecollection");
      system.out.println("collection samplecollection selected successfully"); 
      // 删除对象
      collection.deleteone(filters.eq("title", "mongodb")); 
      system.out.println("document deleted successfully...");  
      
      // 更新之后获取文档 
      // 获取迭代对象
      finditerable 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 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()等的工作方式与后续教程中的解释相同。

查看笔记

扫码一下
查看教程更方便
网站地图