Schema

Figure 795. Schema validation support Slide presentation
db.runCommand( {
  collMod: "group",
  validator: { $jsonSchema: {
     bsonType: "object",
     required: [ "cname", "gid" ],
        properties: {
          cname: {
              bsonType: "string",
              description: 
              "A group's common name"
          },                
          gid: {
             bsonType: "string",
             description: 
             "A group's short name"
          }
       }
     } 
  },
  validationLevel: "moderate"
})

Figure 796. Violating required field Slide presentation
db.group.insert(
 {
   cname: "Extra users"
 }          
... Bulk write operation error on server localhost:27017. 
Write errors: [BulkWriteError{index=0, code=121,
    message='Document failed validation', details={}}].

Figure 797. Schema types Slide presentation

See BSON Types for reference.


Figure 798. Enforcing unique keys Slide presentation
db.group.createIndex({ 
   "cname": 1
  },
  {
      unique: true
})

db.group.insert({cname: "Extra users",
  ...
  }
)
com.mongodb.MongoBulkWriteException:
Bulk write operation error on server localhost:27017.
Write errors: [BulkWriteError{index=0, code=11000, 
message='E11000 duplicate key error collection: 
exploredb.group index: cname_1 dup key: 
  { cname: "Extra users" }', details={}}].

Figure 799. On the downside Slide presentation
  • No way to enforce referential integrity rules.