如何将MongoDB与Java程序连接

时间:2018-10-03 06:57:15

标签: java mongodb driver connectivity

我想将My Java程序与Mongo DB数据库连接。下面我写了我的Java程序。但是它给出了一些错误。

import java.net.UnknownHostException;
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;
import org.bson.*;

public class JavaMongo{

    public static void main(String[] args) 
    {
        try 
        {   
           MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase database = mongoClient.getDatabase("mydb");

        for (String name : database.listCollectionNames()) {

            System.out.println(name);
        }

        mongoClient.close();

        }   
        catch(Exception e)
        {   
           System.out.println(e);
        }   

    }   
}
  

我遇到以下错误

Errors on my terminal.

3 个答案:

答案 0 :(得分:0)

您错过了创建凭证声明。所以基本上这个错误显示尝试此代码。

import java.net.UnknownHostException;
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;
import com.mongodb.MongoCredential;  
import com.mongodb.client.MongoDatabase; 
import org.bson.*;

public class JavaMongo{

    public static void main(String[] args) 
    {
        try 
        {   
           MongoClient mongoClient = new MongoClient("localhost", 27017);
           // Creating Credentials 
          MongoCredential credential; 
          credential = MongoCredential.createCredential("sampleUser", "myDb", 
             "password".toCharArray()); 
        MongoDatabase database = mongoClient.getDatabase("mydb");

        for (String name : database.listCollectionNames()) {

            System.out.println(name);
        }

        mongoClient.close();

        }   
        catch(Exception e)
        {   
           System.out.println(e);
        }   

    }   
}

答案 1 :(得分:0)

您需要导入“ com.mongodb.client.MongoDatabase”以使用MongoDatabase接口。

答案 2 :(得分:0)

maven依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

================================================ ==========================

application.properties

server.port = 8080
spring.data.mongodb.database=user_db
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

================================================ ==========================

以下链接供参考:(逐步说明)

https://www.youtube.com/watch?v=2Tq2Q7EzhSA&t=7s