2

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" }

1 Answer 1

1

Well, you can use the Filters utility class API to build the validator as it described in the documentation. Here is the code:

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

It creates a collection with validation on MongoDB 3.4.

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

1 Comment

Thank you, exactly what I was searching for!

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.