繁体   English   中英

MongoDB 删除所有数据库,除了 admin config 和 local

[英]MongoDB deletes all databases, besides admin config and local

我有一个问题。 我想将 MongoDB 与我的 Java Stuff 一起使用,但我不知道为什么它会不断删除除 admin、config 和 local 之外的所有其他数据库。 我目前在我的本地服务器上使用它。 我已经检查了我的代码,但那里没有删除。

我正在制作一个 minecraft 插件,它连接到数据库并创建 2 个 collections。

好的,我找到了问题所在。 数据库已创建,但由于其为空而立即被删除。 但我想知道为什么,因为如您所见,我正在其中创建两个 collections。

我不知道这是否重要,但我使用异步 mongodb java 驱动程序。

    private final String hostName;
private final String port;

private MongoClient client;
private MongoDatabase database;

private MongoCollection<Document> playerCollection, statsCollection;

public MongoManager(String hostName, String port) {
    this.hostName = hostName;
    this.port = port;
}

public void connect() {
    this.client = MongoClients.create(new ConnectionString(MessageFormat.format("mongodb://{0}:{1}", hostName, port)));

    this.database = this.client.getDatabase("prod");
    this.playerCollection = this.database.getCollection("players");
    this.statsCollection = this.database.getCollection("stats");
}

getCollection方法上指定的集合名称可能存在也可能不存在于 mongodb 上。 如果该集合不存在,MongoDB 将创建它作为写入操作的一部分。

在 MongoDB 中,当您创建集合或将一些数据插入到集合中时,会创建一个数据库。 这是一些代码来证明这一点。

(1) getDatabase方法不创建数据库,而是“访问”名为testDB1的数据库,不管它是否存在。 如果数据库不存在,则不会创建它。 如果存在,您可以访问其中的任何现有 collections。 假设没有名为“testDB1”的数据库,以下代码将创建一个数据库和一个集合。

try(MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017/")) {

    MongoDatabase database = mongoClient.getDatabase("testDB1");
    database.createCollection("testColl");
}

(2) 通过将文档插入该数据库中的集合来创建一个新数据库。

MongoDatabase database = mongoClient.getDatabase("testDB2");
MongoCollection<Document> coll = database.getCollection("testColl");

Document newDoc = Document.parse("{ 'name': 'Mongo' }");
coll.insertOne(newDoc);
System.out.println(coll.find().first().toJson());

笔记:

As of MongoDB Java Driver version 3.9, MongoDB Async Java Driver Documentation says that the callback-based Async Java Driver has been deprecated in favor of the MongoDB Reactive Streams Java Driver.

好的人。 我真的很感谢所有试图回答我问题的人。 在我阅读了@prasad_ 的答案后,我的大脑终于又开始工作了。

我记得mongo-db同步和异步API之间有一个巨大的区别。

当您在同步 API 中执行 getDatabase() 时,如果它返回 null,它将自动为您创建它。

同步 API:

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>LATEST</version>
        <scope>compile</scope>
    </dependency>

异步 API:

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver-async</artifactId>
        <version>LATEST</version>
        <scope>compile</scope>
    </dependency>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM