by Marc-David Militz
Forum: MongoDB Theorie
db.foodColor.drop()
db.createCollection ( "foodColor",
{
validator:
{
$jsonSchema:
{
bsonType: "object",
required: ["name", "box_size", "dyes"],
properties:
{
_id: {},
name: {
bsonType: ["string"],
description: "'name' is a required string"
},
box_size: {
enum: [3, 4, 6],
description: "'box_size' must be one of the values listed and is required"
},
dyes: {
bsonType: ["array"],
minItems: 1, // each box of food color must have at least one color
uniqueItems: true,
additionalProperties: false,
items: {
bsonType: ["object"],
required: ["size", "color"],
additionalProperties: false,
description: "'items' must contain the stated fields.",
properties: {
size: {
enum: ["small", "medium", "large"],
description: "'size' is required and can only be one of the given enum values"
},
color: {
bsonType: "string",
description: "'color' is a required field of type string"
}
}
}
}
}
}
}
})
Unser Paket mit den Lebensmittelfarben, wie wir es oben festgelegt haben, muss eindeutige Tuben mit Farbe enthalten. Die Eindeutigkeit wird über die Kombination aus Größe und Farbe ermittelt.
db.foodColor.insertOne({name: "Rainbow RGB", box_size: 3,
dyes: [
{size: "small", color: "red"},
{size: "medium", color: "green"},
{size: "large", color: "blue"}]}) // works
db.foodColor.insertOne({name: "Singinꞌ the Blues", box_size: 3,
dyes: [
{size: "small", color: "blue"},
{size: "medium", color: "blue"},
{size: "large", color: "blue"}]}) // works
valide ist, weil jede Farbe/Größe Kombination nur einmal vorkommt.
db.foodColor.insertOne({name: "Reds", box_size: 6,
dyes: [
{size: "small", color: "red"},
{size: "medium", color: "red"},
{size: "large", color: "red"},
{size: "small", color: "scarlet"},
{size: "small", color: "brick red"},
{size: "small", color: "red"}
]}) // doesn't work, there are two small red dyes in this box
Da hier zwei "kleine" "rote" Elemente enthalten sind, schlägt das Einfügen fehl.
db.foodColor.insertOne({name: "Specials", box_size: 3,
dyes: [
{size: "small", color: "red", aroma:"malty"},
{size: "medium", color: "red", aroma:"fruity"},
{size: "large", color: "red",taste:"salty"},
]}) // doesn't work, there are extra properties
Das schlägt fehl, weil in unserem Schema nur Größe und Farbe definiert sind. Die zusätzlichen Attribute sind für die Validierung nicht relevant. Die Möglichkeit ein Schema auch anhand der Inhalte zu validieren ist ein mächtiges Werkzeug. Es ermöglicht uns unser abstraktes Validierungsschema, um spezifische Elemente zu erweitern.