📜  MongoDB-Java

📅  最后修改于: 2020-11-27 05:59:35             🧑  作者: Mango


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

安装

在Java程序中开始使用MongoDB之前,需要确保在计算机上设置了MongoDB CLIENT和Java。您可以检查Java教程以在计算机上安装Java。现在,让我们检查如何设置MongoDB CLIENT。

  • 您需要下载jar mongodb-driver-3.11.2.jar及其依赖项mongodb-driver-core-3.11.2.jar。 。确保下载这些jar文件的最新版本。

  • 您需要将下载的jar文件包含到类路径中。

连接到数据库

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

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

import com.mongodb.client.MongoDatabase; 
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  
public class ConnectToDB { 
   
   public static void main( String args[] ) {  
      
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
   
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      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[] ) {  
      
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
     
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      //Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      //Creating a collection 
      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[] ) {  
      
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
     
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      // Creating a collection 
      System.out.println("Collection created successfully"); 
      // Retrieving a collection
      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[] ) {
    
    // Creating a Mongo client
    MongoClient mongo = new MongoClient( "localhost" , 27017 );
    
    // Accessing the database
    MongoDatabase database = mongo.getDatabase("myDb");
    
    // Creating a collection
    database.createCollection("sampleCollection");
    System.out.println("Collection created successfully");
    
    // Retrieving a collection
    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");
    
    //Inserting document into the collection
    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[] ) {
    
        // Creating a Mongo client
        MongoClient mongo = new MongoClient( "localhost" , 27017 );
        
        // Creating Credentials
        MongoCredential credential;
        credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());
        System.out.println("Connected to the database successfully");
        
        // Accessing the database
        MongoDatabase database = mongo.getDatabase("myDb");
        
        // Retrieving a collection
        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.tutorialspoint.com/mongodb/")
        .append("by", "tutorials point");
        Document document2 = new Document("title", "RethinkDB")
        .append("description", "database")
        .append("likes", 200)
        .append("url", "http://www.tutorialspoint.com/rethinkdb/")
        .append("by", "tutorials point");
        List list = new ArrayList();
        list.add(document1);
        list.add(document2);
        collection.insertMany(list);
        // Getting the iterable object
        FindIterable iterDoc = collection.find();
        int i = 1;
        // Getting the iterator
        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.tutorialspoint.com/mongodb/, by=tutorials point}}
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}}

更新文件

要从集合中更新文档,请使用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[] ) {  
      
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
     
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb"); 
      // Retrieving a collection 
      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...");  
      
      // Retrieving the documents after updation 
      // Getting the iterable object
      FindIterable iterDoc = collection.find(); 
      int i = 1; 
      // Getting the iterator 
      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.tutorialspoint.com/mongodb/, by=tutorials point}}
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}}

删除文件

要从集合中删除文档,您需要使用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[] ) {  
   
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb"); 
      // Retrieving a collection
      MongoCollection collection = database.getCollection("sampleCollection");
      System.out.println("Collection sampleCollection selected successfully"); 
      // Deleting the documents 
      collection.deleteOne(Filters.eq("title", "MongoDB")); 
      System.out.println("Document deleted successfully...");  
      
      // Retrieving the documents after updation 
      // Getting the iterable object 
      FindIterable iterDoc = collection.find(); 
      int i = 1; 
      // Getting the iterator 
      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.tutorialspoint.com/rethinkdb/, by=tutorials point}}

删除收藏

要从数据库中删除集合,您需要使用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[] ) {  
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      MongoDatabase database = mongo.getDatabase("myDb");  
      
      // Creating a collection 
      System.out.println("Collections created successfully"); 
      // Retrieving a collection
      MongoCollection collection = database.getCollection("sampleCollection");
      // Dropping a Collection 
      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[] ) {  
      
      // Creating a Mongo client 
      MongoClient mongo = new MongoClient( "localhost" , 27017 ); 
      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createCredential("sampleUser", "myDb", 
         "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  
      
      // Accessing the database 
      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()等的工作方式与后续教程中说明的相同。