MongoDB方法参考打印数据库列表?

问题描述 投票:0回答:1

在这个guide之后,我试图打印出一个数据库列表。

public class Main{
    public static void main(String[] args){
        System.out.println("Testing MongoDB.");
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase database = mongoClient.getDatabase("myMongoDb");
        System.out.println("Connect to database successfully.");

        database.getCollection("Customers");
        System.out.println("Created Customer collection successfully.");

        MongoCursor<String> dbsCursor = database.listCollectionNames().iterator();

        while(dbsCursor.hasNext()){
           System.out.println(dbsCursor.next());
        }

        database.listCollectionNames().forEach((Consumer<String>) System.out::println);
        mongoClient.listDatabaseNames().forEach((Consumer<String>) System.out::println);
    }
}

我也使用常规迭代器测试,但只得到以下输出。

> Task :run
Testing MongoDB.
Dec 27, 2017 1:02:49 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Connect to database successfully.
Created Customer collection successfully.
Dec 27, 2017 1:02:49 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster description not yet available. Waiting for 30000 ms before timing out
Dec 27, 2017 1:02:49 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:23}] to localhost:27017
Dec 27, 2017 1:02:49 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 0]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=2474145}
Dec 27, 2017 1:02:49 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:24}] to localhost:27017
admin
config
local

根据指南,预期产出将是这样的:

The output will be:

local      0.000GB
myMongoDb  0.000GB

我不太确定我做错了什么。另外,有没有办法让日志记录静音,以便我可以更轻松地检查输出?

java mongodb
1个回答
0
投票

如果您需要检查是否存在集合,请尝试以下操作:

boolean collectionExists = client.getDatabase("dbName").listCollectionNames()
.into(new ArrayList<String>()).contains("collectionName")
© www.soinside.com 2019 - 2024. All rights reserved.