3

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?

2
  • Have you found any solution? Commented Nov 8, 2019 at 10:30
  • Yes, just answered my own question. Sorry for not doing it earlier. Commented Nov 14, 2019 at 11:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.