【问题标题】:Creating a collection with validation in MongoDB 3.4 using Java使用 Java 在 MongoDB 3.4 中创建带有验证的集合
【发布时间】:2018-07-16 20:28:25
【问题描述】:

我正在尝试通过 Java 在 MongoDB(3.4) 中创建一个带有验证的集合。

在 shell 中执行时可以正常工作:

  db.createCollection( "accounts",
   {
      validator: { $and:
         [
            { username: { $type: "string" } },
            { email: { $regex: /@*\.*$/ } },
            { password: { $type: "string" } }
         ]
      }
   }
)

所以现在我想用 java 中的验证创建相同的集合。可悲的是,我在这里找到的先前答案正在使用已弃用的方法。

这是我尝试过的,因为验证器字段是一个选项字段。

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

【问题讨论】:

    标签: java json mongodb validation mongodb-query


    【解决方案1】:

    好吧,您可以使用 Filters 实用程序类 API 来构建验证器,如 the documentation 中所述。代码如下:

        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 上创建一个带有验证的集合。

    【讨论】:

    • 谢谢你,正是我正在寻找的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多