Skip to content

Instantly share code, notes, and snippets.

@ianf-mongodb
Last active October 14, 2021 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianf-mongodb/9c8f2ebcbaa3b21c82307e9c54e86dbf to your computer and use it in GitHub Desktop.
Save ianf-mongodb/9c8f2ebcbaa3b21c82307e9c54e86dbf to your computer and use it in GitHub Desktop.
//https://severalnines.com/database-blog/overview-mongodb-schema-validation
db.createCollection("users", {
validator: {
$and: [
{
"name": {$type: "string", $exists: true}
},
{
"mobile": {$type: "string", $regex: /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/}
},
{
"email": {$type: "string", $exists: true}
}
]
}
});
db.runCommand(
{
insert: "users",
documents: [ {status: "A" } ],
bypassDocumentValidation: true
}
)
db.runCommand( { validate: "users" } );
/*
{
ns: 'Debug.users',
nInvalidDocuments: 0,
nrecords: 1,
nIndexes: 1,
keysPerIndex: { _id_: 1 },
indexDetails: { _id_: { valid: true } },
valid: true,
repaired: false,
warnings: [
"Detected one or more documents not compliant with the collection's schema. See logs."
],
errors: [],
extraIndexEntries: [],
missingIndexEntries: [],
corruptRecords: [],
ok: 1
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment