使用Java在MongoDB 3.4中创建具有验证的集合
我试图通过Java在MongoDB(3.4)中创建一个具有验证的集合 当在shell中执行时,这可以正常工作:使用Java在MongoDB 3.4中创建具有验证的集合,java,json,mongodb,validation,mongodb-query,Java,Json,Mongodb,Validation,Mongodb Query,我试图通过Java在MongoDB(3.4)中创建一个具有验证的集合 当在shell中执行时,这可以正常工作: db.createCollection( "accounts", { validator: { $and: [ { username: { $type: "string" } }, { email: { $regex: /@*\.*$/ } }, { password: {
db.createCollection( "accounts",
{
validator: { $and:
[
{ username: { $type: "string" } },
{ email: { $regex: /@*\.*$/ } },
{ password: { $type: "string" } }
]
}
}
)
所以现在我想用java创建相同的集合,并进行验证。遗憾的是,我在这里找到的以前的答案使用的是不推荐的方法
这是我尝试的,因为validator字段是一个选项字段
//String createDatabase = "{ 'validator': { '$and':[{ 'username': { '$type': 'string' } },{ 'email': { '$regex': '@*.*$' } },{ 'password': { '$type': 'string' } }]}}";
String createDatabase = " { \"validator\": { \"$and\":[{ \"username\": { \"$type\": \"string\" } },{ \"email\": { \"$regex\": \"@*.*$\" } },{ \"password\": { \"$type\": \"string\" } }]}}";
JsonParser jsonParser = new JsonParser();
DBObject dbobj= (DBObject) JSON.parse(createDatabase);
getMongoClient().getDatabase(DATABASE_NAME).createCollection(collectionName, new CreateCollectionOptions().validationOptions(new ValidationOptions().validator((Bson) dbobj)) );
这是我得到的例外。我假设这是因为json无法解析,我检查了它是否有效,是否应该有效
{
"validator": { "$and":
[
{ "username": { "$type": "string" } },
{ "email": { "$regex": "@*.*$" } },
{ "password": { "$type": "string" } }
]
}
}
上面是我试图解析的json
com.mongodb.MongoCommandException: Command failed with error 2: 'unknown operator: $and' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "unknown operator: $and", "code" : 2, "codeName" : "BadValue" }
您可以使用过滤器实用程序类API来构建验证程序,如中所述。代码如下:
Bson username = Filters.type("username", BsonType.STRING);
Bson email = Filters.regex("email", "@*.*$");
Bson password = Filters.type("password", BsonType.STRING);
Bson validator = Filters.and(username, email, password);
ValidationOptions validationOptions = new ValidationOptions()
.validator(validator);
database.createCollection("accounts", new CreateCollectionOptions()
.validationOptions(validationOptions));
它在MongoDB 3.4上创建了一个带有验证的集合。谢谢,这正是我要搜索的!