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

Viewed 526

Using the MongoDB Java driver I would like to retrieve a validator defined for a collection. In mongo Shell this can be easily achieved by running db.getCollectionInfos({name: "MyTestCollection"})[0].options.validator; as described here.

What I miss is a similar method on the MongoDatabase class or a Database Command I can run with the MongoDatabase.runCommand(...) method.

What do I miss? How to retrieve that information in Java?

1 Answers

This is how I managed to retrieve the schema in question:

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

Usage is straightforward:

new MongoDbJsonSchemaRetriever(yourDatabase).retrieveJsonSchema(yourCollectionName)

You will retrieve either the schema or an empty document if no schema is defined/found.

Let me know if you have found a better way.

Related