簡體   English   中英

如何使用 Java 驅動程序檢索現有 MongoDB 集合的驗證器?

[英]How to retrieve validator for an existing MongoDB collection using Java driver?

使用 MongoDB Java 驅動程序,我想檢索為集合定義的驗證器 在 mongo Shell 中,這可以通過運行db.getCollectionInfos({name: "MyTestCollection"})[0].options.validator;輕松實現db.getCollectionInfos({name: "MyTestCollection"})[0].options.validator; 作為描述在這里

我想念的是MongoDatabase類上的類似方法或我可以使用MongoDatabase.runCommand(...)方法運行的數據庫命令

我想念什么? 如何在 Java 中檢索該信息?

這就是我設法檢索相關架構的方式:

...
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)

如果未定義/找到架構,您將檢索架構或空文檔。

如果您找到更好的方法,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM