Using Pymongo
to set/query/insert in my mongodb
database.
It is possible to indicate that a value should be a unique index in mongodb.
db.mycoll.create_index("sid", unique=True) # This is what I have so far
Now, I want to make sure that the index has a minimum and maximum length. (3-20 chars).
I didn't find any information about adding length restrictions, is it possible with mongodb ?
I would expect something like this:
db.mycoll.create_index("sid", unique=True, max_len=20, min_len=3) # Is there a way to do this ?
If you need a bit more context, I have a collection in mongodb and for every document I need a SID
(string ID). I would like to put a technical size limit on this value, so I can be sure on every side of my application that any string which doesn't match this size is not a proper id.
Thanks a lot
CodePudding user response:
You can use the MongoDB Schema Validation to specify the maximum and minimum length of a string type field. For example,
db.createCollection("mycoll", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "city" ],
properties: {
name: {
bsonType: "string",
minLength: 3,
maxLength: 20,
description: "must be a string (3 to 20 chars) and is required"
},
city: {
bsonType: "string"
}
}
}
}
} )
The createCollection
method has the validator
option where you can specify the $jsonSchema to match the documents in the schema. Also, you can specify the validationAction
(default is "error") and validationLevel
(default is "strict") for the validator.
This means, if you try the following insert action, it will fail. The document will not be inserted, as the name
field is only 2 characters in length.
db.mycoll.insertOne({name: 'mo', city: 'los angeles' })
NOTE:
- You still need to create a Unique Index on the
name
field to make sure it doesn't allow duplicate values. - Schema Validation is applied on the database server - just like the unique index.
[EDIT ADD] The PyMongo version:
client = pymongo.MongoClient()
db = client['test']
db.create_collection('pycoll', validator={
'$jsonSchema': {
'bsonType': 'object',
'required': [ 'name' ],
'properties': {
'name': {
'bsonType': 'string',
'minLength': 3,
'maxLength': 20,
'description': 'must be a string (3 to 20 chars) and is required'
}
}
}
}
)
print('Collection created...')