MongoDB 3.4下使用Java创建带验证规则的集合遇异常
解决MongoDB 3.4 Java创建带验证规则集合的异常问题
我之前在MongoDB 3.4环境下用Java创建带验证规则的集合时,也碰到过一模一样的问题——Shell里跑的好好的,Java代码一写就抛异常,刚开始也以为是JSON格式的问题,后来才发现是驱动对参数的处理方式和Shell不一样。
先确认Shell中的正确写法
首先,你在Shell里执行的创建命令大概是这样的(假设你的验证规则用了JSON Schema):
db.createCollection("users", { validator: { $jsonSchema: { bsonType: "object", required: ["name", "email"], properties: { name: { bsonType: "string", description: "must be a string and is required" }, email: { bsonType: "string", pattern: "^.+@.+$", description: "must be a valid email address" } } } }, validationLevel: "strict", validationAction: "error" })
这个写法没问题,但直接把对应的JSON字符串搬到Java里就会出问题。
常见错误:直接传递JSON字符串给validator
很多人会犯的错误是把验证规则写成JSON字符串,直接塞进Document的validator字段里,比如:
// 错误写法!会导致解析异常 String validatorJson = "{ '$jsonSchema': { ... } }"; Document options = new Document("validator", validatorJson); db.createCollection("users", options);
原因很简单:MongoDB服务器期望validator是一个BSON对象,而Java驱动如果传字符串的话,会把它当作普通字符串值发送给服务器,服务器自然无法解析成验证规则,进而抛出异常。
正确的写法:用Document构建验证规则
你需要用org.bson.Document来逐层构建验证规则的BSON结构,而不是用字符串。下面是完整的可运行示例:
import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class ValidatedCollectionCreator { public static void main(String[] args) { // 连接MongoDB(3.4版本用MongoClient,新版用MongoClients) try (MongoClient mongoClient = new MongoClient("localhost", 27017)) { MongoDatabase database = mongoClient.getDatabase("your_db_name"); // 构建JSON Schema验证规则 Document validator = new Document("$jsonSchema", new Document() .append("bsonType", "object") .append("required", new String[]{"name", "email"}) .append("properties", new Document() .append("name", new Document("bsonType", "string") .append("description", "must be a string and is required")) .append("email", new Document("bsonType", "string") .append("pattern", "^.+@.+$") .append("description", "must be a valid email address")))); // 构建集合创建选项 Document createOptions = new Document("validator", validator) .append("validationLevel", "strict") .append("validationAction", "error"); // 创建集合 database.createCollection("users", createOptions); System.out.println("带验证规则的集合创建成功!"); } catch (Exception e) { e.printStackTrace(); } } }
如果你偏爱JSON字符串:用Document.parse()转换
如果你还是想用JSON字符串来编写验证规则(比如更直观),可以用Document.parse()方法把合法的JSON转换成Document对象,注意要正确转义引号(或者用Java 15+的文本块):
// Java 15+ 文本块写法,无需转义引号 String validatorJson = """ { "$jsonSchema": { "bsonType": "object", "required": ["name", "email"], "properties": { "name": { "bsonType": "string", "description": "must be a string and is required" }, "email": { "bsonType": "string", "pattern": "^.+@.+$", "description": "must be a valid email address" } } } } """; Document validator = Document.parse(validatorJson); // 然后和上面一样构建createOptions,再创建集合
额外注意事项
- 确保你的Java驱动版本和MongoDB服务器版本兼容,MongoDB 3.4建议搭配3.6.x版本的驱动(不要用太新的4.x驱动,避免兼容性问题)。
- 验证规则里的
$jsonSchema关键字要注意大小写,MongoDB是区分大小写的。
内容的提问来源于stack exchange,提问作者rhewid
相关产品推荐
相关产品推荐

