无法使用Mongo Java驱动程序创建数据库

问题描述:

我是mongo数据库的新手,刚刚学习基础知识。我想我的显示当前数据库的名称:无法使用Mongo Java驱动程序创建数据库

try { 
     // Creates a new instance of MongoDBClient and connect to localhost 
     // port 27017 
     MongoClient mongoClient = new MongoClient("localhost", 27017); 

     mongoClient.getDB("myMongoDB"); 

     List<String> listofDB= mongoClient.getDatabaseNames(); 

     for(String dbName : listofDB){ 
      System.out.println(dbName); 
     } 



    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

它打印出的唯一的数据库是adminlocalmyMongoDB未出现。当我在外壳上输入并输入show databases时,myMongoDB也不会出现。我真的很困惑,因为通过使用.getDB()方法,如果传递到该方法的字符串不是当前数据库的名称,然后蒙戈将创建一个名称的数据库.. here

我使用以下依赖:

  `<dependency> 
      <groupId>org.mongodb</groupId> 
      <artifactId>mongo-java-driver</artifactId> 
      <version>2.12.3</version> 
      </dependency>` 

这将不打印myMongoDB,因为它尚未创建。 您需要执行一些事务,如创建集合,将数据插入集合。然后它将显示在该列表中。 只有选择数据库才能在mongo数据库中创建数据库。

由于mongodb的默认行为是懒惰地创建数据库,直到创建文档插入。

你可以按照这个链接做使用Java驱动程序Mongo的一些操作: http://mongodb.github.io/mongo-java-driver/2.13/getting-started/quick-tour/

如果你想使用命令行比你可以按照这个链接创建集合: https://docs.mongodb.com/manual/reference/method/db.createCollection/

你有没有尝试手动创建数据库然后运行代码?在这种情况下,我不认为myMongoDB存在。为了让一个在外壳做use myMongoDB

编辑:你也必须把至少一个集合放入数据库为它创建。 https://www.tutorialspoint.com/mongodb/mongodb_create_database.htm

link中所述,getDB方法已被弃用。使用MongoClient.getDatabase(String databaseName)方法来创建。

当第一个文档被保存到集合中时,MongoDB会隐式地创建一个集合。 createCollection()方法仅在将选项对象作为参数传递给它时才显式创建集合。通过link去进一步的信息

MongoClient mongoClient = new MongoClient(); 
MongoCursor<String> dbsCursor = mongoClient.listDatabaseNames().iterator(); 
while(dbsCursor.hasNext()) { 
    System.out.println(dbsCursor.next()); 
} 

还要检查你的dpath(因为外壳没有返回你的数据库,可能是其不正道)

尝试mongod --dbpath /your/path

此外,仅在将文档插入到数据库中的集合中才会实际创建数据库,这将隐式地创建集合和数据库。