如何使用Java驱动程序检索现有MongoDB集合的验证器?

时间:2018-11-08 13:38:17

标签: java mongodb mongodb-java

使用MongoDB Java驱动程序,我想检索为集合定义的validator。在mongo Shell中,可以按照here所述运行Vue.component("bs-select",{ template: `<select :value="value" v-on:change="changeVal" style="width: 100%"> <option value="" selected disabled>Choose...</option> <option v-if="!options">{{ value }}</option> <option v-for="option in options" :value="option.value">{{ option.text }}</option> </select>`, props: ["value", "options"], methods: { changeVal: function(event) { this.$emit('change-value', event.target.value) } } }); new Vue({ el: "#app", data: { test: "bug", options: [ { value: "hello", text: "Hello" }, { value: "bug", text: "Bug" } ] } }) 来轻松实现这一点。

我错过的是MongoDatabase类上的类似方法,或者我可以使用db.getCollectionInfos({name: "MyTestCollection"})[0].options.validator;方法运行的Database Command

我想念什么?如何用Java检索该信息?

1 个答案:

答案 0 :(得分: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)

如果未定义/找到任何模式,则将检索该模式或一个空文档。

让我知道您是否找到了更好的方法。