I am trying to create a collection with validation in MongoDB(3.4) via Java.
This is working fine when executed in the shell:
db.createCollection( "accounts",
{
validator: { $and:
[
{ username: { $type: "string" } },
{ email: { $regex: /@*\.*$/ } },
{ password: { $type: "string" } }
]
}
}
)
So now I wanted to create the same collection with that validation in java. Sadly the previous answers I have found here are using deprecated methods.
This is what I tried since the validator field is an option field.
//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)) );
This is the exception I got. I assume that's because somehow the json cannot be parsed, I checked back if it's valid and it should be.
{
"validator": { "$and":
[
{ "username": { "$type": "string" } },
{ "email": { "$regex": "@*.*$" } },
{ "password": { "$type": "string" } }
]
}
}
Above is the json that I tried to parse.
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" }