【问题标题】:How to retrieve validator for an existing MongoDB collection using Java driver?如何使用 Java 驱动程序检索现有 MongoDB 集合的验证器?
【发布时间】:2018-11-08 13:38:17
【问题描述】:

使用 MongoDB Java 驱动程序,我想检索为集合定义的 validator。在 mongo Shell 中,这可以通过运行db.getCollectionInfos({name: "MyTestCollection"})[0].options.validator; 轻松实现,如here 所述。

我想念的是MongoDatabase 类或Database Command 上的类似方法,我可以使用MongoDatabase.runCommand(...) 方法运行。

我错过了什么?如何在 Java 中检索该信息?

【问题讨论】:

  • 你找到解决办法了吗?
  • 是的,刚刚回答了我自己的问题。很抱歉没有早点这样做。

标签: java mongodb mongodb-java


【解决方案1】:

这就是我设法检索相关架构的方式:

...
MongoDbJsonSchemaRetriever(MongoDatabase database) {
    this.database = database;
}

Document retrieveJsonSchema(String collectionName) {
    Document collection = database.listCollections().filter(byName(collectionName)).first();
    return readJsonSchema(collection);
}

private Bson byName(String collectionName) {
    return Filters.eq("name", collectionName);
}

private static Document readJsonSchema(Document collection) {
    return collection.get("options", EMPTY).get("validator", EMPTY).get("$jsonSchema", EMPTY);
}

用法很简单:

new MongoDbJsonSchemaRetriever(yourDatabase).retrieveJsonSchema(yourCollectionName)

如果未定义/找到架构,您将检索架构或空文档。

如果你找到了更好的方法,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多