Mongodb Session 2
Mongodb Session 2
Result:
db.restaurant.updateOne(
{ "name" : "Central Perk Cafe" },
{ $set: { "violations" : 3 } }
);
}
db.restaurant.replaceOne(
{ "name" : "Central Perk Cafe" },
{ "name" : "Central Pork Cafe", "Borough" : "Manhattan" }
);
}
Delete Methods:
db.collection.remove()
Delete a single document or all documents that match a
specified filter.
db.users.remove({})
db.collection.deleteMany():
Delete all documents that match a specified filter.
The following example uses the method to
delete all documents from the users collection:
db.users.deleteMany({})
Note:
If the users collection already contains documents with the
same _id values, you need to drop the collection (db.users.drop())
before inserting the example documents.
The key decision in designing data models
for Mongo DB applications revolves around
the structure of documents and how the
application represents relationships
between data.
There are two tools that allow applications
to represent these relationships:
➢ Reference documents
➢ Embedded documents
Data
Modeling Reference documents:
References store the relationships between
data by including links or references from
one document to another.
Broadly, these are normalized data
models.
Consider the following diagram:
{ patron_id: "joe",
street: "123 Fake Street",
city: "Faketon",
Address
state: "MA",
document
zip: "12345"
}
If the address data is frequently retrieved with the name
information, then with referencing, your application needs to
issue multiple queries to resolve the reference.
The better data model would be to embed the address data
in the patron data, as in the following document:
{
_id: "joe",
name: "Joe Bookreader",
address: {
street: "123 Fake Street",
Embedd
ed city: "Faketon",
docume
state: "MA",
nts
zip: "12345"
}
}
Model One-to-Many Relationships with
Embedded Documents:
Consider the following example that maps patron and multiple
address relationships.
In this one-to-many relationship between patron and address
data, the patron has multiple address entities.
{
_id: "joe“, patron
document
name: "Joe Bookreader"
}
{
patron_id: "joe",
street: "123 Fake Street", addres1
city: "Faketon", document
state: "MA",
zip: "12345"
}
{
patron_id: "joe",
street: "1 Some Other Street", Address2
city: "Boston", document
state: "MA",
zip: "12345"
}
Publisher have
book reference
since have
limited number of
books
{
_id: 123456789,
title: "MongoDB: The Definitive Guide",
author: [ "Kristina Chodorow", "Mike Dirolf" ],
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English"
} Book
document
{
_id: 234567890,
title: "50 Tips and Tricks for MongoDB Developer",
author: "Kristina Chodorow",
published_date: ISODate("2011-05-06"),
pages: 68,
language: "English"
}
To avoid mutable, growing arrays, store the publisher reference
inside the book document:
{
_id: "oreilly",
name: "O'Reilly Media", Publisher
founded: 1980, document
location: "CA"
}
Book
{ document
_id: 123456789, have
publisher
title: "MongoDB: The Definitive Guide", reference
author: [ "Kristina Chodorow", "Mike Dirolf" ], since have
large
published_date: ISODate("2010-09-24"),
number of
pages: 216, books
language: "English",
publisher_id: "oreilly"
}
Another book with same publisher reference inside document:
{
_id: 234567890,
title: "50 Tips and Tricks for MongoDB Developer",
author: "Kristina Chodorow",
published_date: ISODate("2011-05-06"),
pages: 68,
language: "English",
publisher_id: "oreilly"
} Book
document
have
publisher
reference
since have
large
number of
books
Model Tree Structures:
Accessing Nodes:
Model Tree Structures with Parent References
Presents a data model that organizes documents in a tree-like
structure by storing references to “parent” nodes in “child” nodes.
Model Tree Structures with Child References
Presents a data model that organizes documents in a tree-like
structure by storing references to “child” nodes in “parent” nodes.
Model Tree Structures with an Array of Ancestors
Presents a data model that organizes documents in a tree-like
structure by storing references to “parent” nodes and an array
that stores all ancestors.
Model Tree Structures with Materialized Paths
Presents a data model that organizes documents in a tree-like
structure by storing full relationship paths between documents.
Model Tree Structures with Nested Sets
Presents a data model that organizes documents in a tree-like
structure using the Nested Sets pattern. This optimizes discovering
subtrees at the expense of tree mutability.
Model Tree
Structures with Parent
References:
The Parent References pattern stores each tree
node in a document; in addition to the tree node,
the document stores the id of the node’s parent.
db.categories.insert( { _id: "MongoDB", parent:
"Databases" } )
db.categories.insert( { _id: "dbm", parent: "Databases"
})
db.categories.insert( { _id: "Databases", parent:
"Programming" } )
db.categories.insert( { _id: "Languages", parent:
"Programming" } )
db.categories.insert( { _id: "Programming", parent:
"Books" } )
db.categories.insert( { _id: "Books", parent: null } )
The query to retrieve the parent of a node is fast and
straightforward:
db.categories.findOne( { _id: "MongoDB" } ).parent
db.categories.createIndex( { children: 1 } )
You can query for a node in the children field to find its
parent node as well as its siblings:
db.categories.createIndex( { ancestors: 1 } )
You can use regular expressions on the path field to find the
descendants of Programming:
db.categories.find( { path: /,Programming,/ } )
The Nested Sets pattern provides a fast and efficient solution for
finding subtrees but is inefficient for modifying the tree structure
As such, this pattern is best for static trees that do not change
Schema Validation:
MongoDB provides the capability to perform schema validation
during updates and insertions.
Specify Validation Rules:
To specify validation rules when creating a new collection, use
db.createCollection() with the validator option.
To add document validation to an existing collection, use
collMod command with the validator option.
MongoDB also provides the following related options:
validationLevel option, which determines how strictly MongoDB
applies validation rules to existing documents during an update,
validationAction option, which determines whether MongoDB
should error and reject documents that violate the validation
rules or warn about the violations in the log but allow invalid
documents.
JSON Schema:
To specify JSON Schema validation, use the $jsonSchema
operator in your validator expression.
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
properties: {
name: {
bsonType: "string",
},
year: {
bsonType: "int",
minimum: 2017,
maximum: 3017,
and is required"
},}}
major: {
},
gpa: {
bsonType: [ "double" ],
},
address: {
bsonType: "object",
JSON
required: [ "city" ],
Validator
properties: {
Schema
street: {
bsonType: "string",
},
city: {
bsonType: "string",
}
MongoDB supports validation with other query operators, with the
exception of the $near, $nearSphere, $text, and $where
operators.
db.createCollection( "contacts",
{ validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
}
})
Behavior:
Validation occurs during updates and inserts.
When you add validation to a collection, existing documents do
not undergo validation checks until modification.
Existing Documents
The validationLevel option determines which operations MongoDB
applies the validation rules:
If the validationLevel is strict (the default), MongoDB applies
validation rules to all inserts and updates.
If the validationLevel is moderate, MongoDB applies validation
rules to inserts and to updates to existing documents that already
fulfill the validation criteria.
With the moderate level, updates to existing documents that do
not fulfill the validation criteria are not checked for validity.
db.contacts.insert([
{ "_id": 1, "name": "Anne", "phone": "+1 555 123 456", "city": "London",
"status": "Complete" },
{ "_id": 2, "name": "Ivan", "city": "Vancouver" }
])
db.runCommand( {
collMod: "contacts",
validator: { $jsonSchema: {
bsonType: "object",
required: [ "phone", "name" ],
properties: {
Validator to
phone: {
contact
bsonType: "string", collection
description: "must be a string and is required"
},
name: {
bsonType: "string",
description: "must be a string and is required"
}
}
} },
validationLevel: "moderate"
})
The contacts collection now has a validator with the moderate
validationLevel:
If you attempted to update the document with _id of 1,
MongoDB would apply the validation rules since the existing
document matches the criteria.
In contrast, MongoDB will not apply validation rules to updates
to the document with _id of 2 as it does not meet the
validation rules.
To disable validation entirely, you can set validationLevel to off.
Accept or Reject Invalid Documents:
The validationAction option determines how MongoDB handles
documents that violate the validation rules:
If the validationAction is error (the default), MongoDB rejects any
insert or update that violates the validation criteria.
If the validationAction is warn, MongoDB logs any violations but
allows the insertion or update to proceed.
For example, create a contacts2 collection with the following JSON Schema
db.createCollection( "contacts2", {
validator: { $jsonSchema: {
bsonType: "object",
required: [ "phone" ],
properties: {
phone: {
pattern : "@mongodb\.com$",
},
status: {
} },
validationAction: "warn"
} )a validator:
With the warn validationAction, MongoDB logs any violations
but allows the insertion or update to proceed.
For example, the following insert operation violates the
validation rule:
db.contacts2.insert( { name: "Amanda", status: "Updated" } )
Data Modeling
Summary:
Model Tree Structrue
Schema Validation
Thank You………
If you have any quries please write to [email protected]".