100% found this document useful (1 vote)
91 views47 pages

Mongodb Session 2

The document discusses various methods in MongoDB for updating and deleting documents in a collection. It provides examples of using the updateOne(), updateMany(), replaceOne(), and unset() methods to update fields in matching documents. It also provides examples of using remove(), deleteOne(), and deleteMany() to delete documents from a collection.

Uploaded by

star
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
91 views47 pages

Mongodb Session 2

The document discusses various methods in MongoDB for updating and deleting documents in a collection. It provides examples of using the updateOne(), updateMany(), replaceOne(), and unset() methods to update fields in matching documents. It also provides examples of using remove(), deleteOne(), and deleteMany() to delete documents from a collection.

Uploaded by

star
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Presentation by Uplatz

Contact Us: https://training.uplatz.com/


Email: [email protected]
Phone:+44 7836 212635
Table of Contents

 Part 2: Update and Delete collection


 Data Modeling
 Model Tree Structrue
 Schema Validation
Update Methods:
MongoDB provides the following methods for updating documents in
a collection:
db.collection.updateOne():
Updates at most a single document that match a specified filter
even though multiple documents may match the specified filter.
db.collection.updateMany():
Update all documents that match a specified filter.
db.collection.replaceOne():
Replaces at most a single document that match a specified filter
even though multiple documents may match the specified filter.
db.collection.update():
Either updates or replaces a single document that match a specified
filter or updates all documents that match a specified filter.
Updating documents:

db.myCollection.update({age : 20}, {$set: {age: 23}})

Result:

 It is always better to use something like _id to update a unique


row.
 This is because multiple fields can have same age and name.
 Therefore, if you update a single row, it will affect all rows which
have same name and age.
UpdateOne:

db.restaurant.updateOne(
{ "name" : "Central Perk Cafe" },
{ $set: { "violations" : 3 } }
);
}

The operation returns:


{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
If no matches were found, the operation instead returns:

{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }


 Replace :

db.restaurant.replaceOne(
{ "name" : "Central Perk Cafe" },
{ "name" : "Central Pork Cafe", "Borough" : "Manhattan" }
);
}

The operation returns:


{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
If no matches were found, the operation instead returns:

{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }


 If you need to remove a property from a single document, you
could do something like this (let’s say you want age to be gone)

db.myCollection.update({name: "navindu"}, {$unset: age});

Delete Methods:
db.collection.remove()
 Delete a single document or all documents that match a
specified filter.
db.users.remove({})

 Alternatively, the following example to remove all documents


from the users collection where the status field equals "P":

db.users.remove( { status : "P" } )


db.collection.deleteOne()
 Delete at most a single document that match a specified filter
even though multiple documents may match the specified
filter.
 The following example uses to delete the first document
where status is "D".
db.users.deleteOne( { status: "D" } )

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({})

 The method returns a document with the status of the


operation
 { "acknowledged" : true, "deletedCount" : 7 }
 The following example uses to remove all documents from
the users collection where the status field equals "A":

db.users.deleteMany({ status : "A" })

 The method returns a document with the status of the


operation:
{ "acknowledged" : true, "deletedCount" : 3 }

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:

 To represent more complex many-to-many relationships.


 To model large hierarchical data sets.
 References provides more flexibility than embedding.
 However, client-side applications must issue follow-up queries to
resolve the references. In other words, normalized data models can
require more round trips to the server.
Embedded Data Models:
 In MongoDB, you may embed related data in a single
structure or document.
 These schema are generally known as “denormalized”
models, and take advantage of MongoDB’s rich
documents.
Consider the following diagram:
 Embedded data models allow applications to store related
pieces of information in the same database record.
 As a result, applications may need to issue fewer queries and
updates to complete common operations.
 In general, embedding provides better performance for read
operations, as well as the ability to request and retrieve
related data in a single database operation.
 Embedded data models make it possible to update related
data in a single atomic write operation

Model One-to-One Relationships with Embedded Documents:


 In this one-to-one relationship
between patron and address data, the address belongs to
the patron.
 In the normalized data model, the address document
contains a reference to the patron document.
Example:
{
_id: "joe",
name: "Joe Bookreader”
Patron }
document

{ 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"
}

 If your application frequently retrieves the address data with the


name information, then your application needs to issue multiple
queries to resolve the references.
 A more optimal schema would be to embed the address data
entities in the patron data, as in the following document:
 With the embedded data model, your application can retrieve the
complete patron information with one query.
{ _id: "joe",
name: "Joe Bookreader",
addresses: [
Embedded
{
documents
street: "123 Fake Street",
city: "Faketon",
state: "MA",
zip: "12345"
},
{
street: "1 Some Other Street",
city: "Boston",
state: "MA",
zip: "12345"
}
] }
One-to-Many Relationships with
Document References :
 Embedding the publisher document inside the book document
would lead to repetition of the publisher data, as the following
documents show:
{
title: "MongoDB: The Definitive Guide",
author: [ "Kristina Chodorow", "Mike Dirolf" ],
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English",
publisher: {
name: "O'Reilly Media",
founded: 1980,
location: "CA"
}
}
{
title: "50 Tips and Tricks for MongoDB Developer",
author: "Kristina Chodorow",
published_date: ISODate("2011-05-06"),
pages: 68,
language: "English", Publisher is
embedded
publisher: {
inside book
name: "O'Reilly Media", document
founded: 1980,
location: "CA"
}
}
 To avoid repetition of the publisher data, use references and
keep the publisher information in a separate collection from
the book collection.
 If the number of books per publisher is small with limited
growth, storing the book reference inside the publisher
document may sometimes be useful.
 Otherwise, if the number of books per publisher is unbounded,
this data model would lead to mutable, growing arrays, as in
the following example:
{
name: "O'Reilly Media",
founded: 1980,
location: "CA",
books: [123456789, 234567890, ...]
}

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

 You can create an index on the field parent to enable fast


search by the parent node:
db.categories.createIndex( { parent: 1 } )

 You can query by the parent field to find its immediate


children nodes:
db.categories.find( { parent: "Databases" } )
Model Tree
Structures with Child
References:
 The Child References pattern stores each tree
node in a document; in addition to the tree
node, document stores in an array the id(s) of the
node’s children.
db.categories.insert( { _id: "MongoDB", children: [] } )
db.categories.insert( { _id: "dbm", children: [] } )
db.categories.insert( { _id: "Databases", children: [
"MongoDB", "dbm" ] } )
db.categories.insert( { _id: "Languages", children: [] }
)
db.categories.insert( { _id: "Programming", children: [
"Databases", "Languages" ] } )
db.categories.insert( { _id: "Books", children: [
"Programming" ] } )
 The query to retrieve the immediate children of a node is
fast and straightforward:
db.categories.findOne( { _id: "Databases" } ).children

 You can create an index on the field children to enable


fast search by the child nodes:

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.find( { children: "MongoDB" } )


Model Tree Structures
with an Array of
Ancestors:
 The Array of Ancestors pattern stores each tree
node in a document; in addition to the tree
node, document stores in an array the id(s) of
the node’s ancestors or path.
db.categories.insert( { _id: "MongoDB", ancestors: [
"Books", "Programming", "Databases" ], parent:
"Databases" } )
db.categories.insert( { _id: "dbm", ancestors: [ "Books",
"Programming", "Databases" ], parent: "Databases" } )
db.categories.insert( { _id: "Databases", ancestors: [
"Books", "Programming" ], parent: "Programming" } )
db.categories.insert( { _id: "Languages", ancestors: [
"Books", "Programming" ], parent: "Programming" } )
db.categories.insert( { _id: "Programming", ancestors: [
"Books" ], parent: "Books" } )
db.categories.insert( { _id: "Books", ancestors: [ ], parent:
null } )
 The query to retrieve the immediate ancestors of a node is
fast and straightforward:
db.categories.findOne( { _id: "MongoDB" } ).ancestors

 You can create an index on the field ancestors to enable


fast search by the ancestors nodes:

db.categories.createIndex( { ancestors: 1 } )

 You can query by the field ancestors to find all its


descendants:

db.categories.find( { ancestors: "Programming" } )


Model Tree Structures
with Materialized
Paths:
 The Materialized Paths pattern stores each tree
node in a document; in addition to the tree
node, document stores as a string the id(s) of
the node’s ancestors or path
db.categories.insert( { _id: "Books", path: null } )
db.categories.insert( { _id: "Programming", path: ",Books,"
})
db.categories.insert( { _id: "Databases", path:
",Books,Programming," } )
db.categories.insert( { _id: "Languages", path:
",Books,Programming," } )
db.categories.insert( { _id: "MongoDB", path:
",Books,Programming,Databases," } )
db.categories.insert( { _id: "dbm", path:
",Books,Programming,Databases," } )
 You can query to retrieve the whole tree, sorting by the field
path:
db.categories.find().sort( { path: 1 } )

 You can use regular expressions on the path field to find the
descendants of Programming:
db.categories.find( { path: /,Programming,/ } )

 You can also retrieve the descendants of Books where the


Books is also at the topmost level of the hierarchy:

db.categories.find( { path: /^,Books,/ } )

 To create an index on the field path use the following


invocation:
db.categories.createIndex( { path: 1 } )
Model Tree Structures
with Nested Sets:

 The Nested Sets pattern identifies each node in


the tree as stops in a round-trip traversal of the
tree. The application visits each node in the
tree twice; first during the initial trip, and second
during the return trip.
db.categories.insert( { _id: "Books", parent: 0, left: 1, right:
12 } )
db.categories.insert( { _id: "Programming", parent:
"Books", left: 2, right: 11 } )
db.categories.insert( { _id: "Languages", parent:
"Programming", left: 3, right: 4 } )
db.categories.insert( { _id: "Databases", parent:
"Programming", left: 5, right: 10 } )
db.categories.insert( { _id: "MongoDB", parent:
"Databases", left: 6, right: 7 } )
db.categories.insert( { _id: "dbm", parent: "Databases",
left: 8, right: 9 } )
 Nested Sets pattern stores each tree node in a document; in
addition to the tree node, document stores the id of node’s
parent, the node’s initial stop in the left field, and its return stop
in the right field.
 You can query to retrieve the descendants of a node:

var databaseCategory = db.categories.findOne( { _id:


"Databases" } );
db.categories.find( { left: { $gt: databaseCategory.left }, right: { $lt:
databaseCategory.right } } );

 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",

required: [ "name", "year", "major", "address" ],

properties: {

name: {

bsonType: "string",

description: "must be a string and is required"

},

year: {

bsonType: "int",

minimum: 2017,

maximum: 3017,

description: "must be an integer in [ 2017, 3017 ]

and is required"

},}}
major: {

enum: [ "Math", "English", "Computer Science", "History", null ],

description: "can only be one of the enum values and is required"

},

gpa: {

bsonType: [ "double" ],

description: "must be a double if the field exists"

},

address: {

bsonType: "object",
JSON
required: [ "city" ],
Validator
properties: {
Schema
street: {

bsonType: "string",

description: "must be a string if the field exists"

},

city: {

bsonType: "string",

"description": "must be a string and is required"

}
 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: {

bsonType: "string", Contact2


description: "must be a string and is required" collection with
}, validation
email: { schema
bsonType : "string",

pattern : "@mongodb\.com$",

description: "must be a string and match the regular expression pattern"

},

status: {

enum: [ "Unknown", "Incomplete" ],

description: "can only be one of the enum values"

} },

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" } )

 However, since the validationAction is warn only, MongoDB


only logs the validation violation message and allows the
operation to proceed:

2017-12-01T12:31:23.738-0500 W STORAGE [conn1] Document


would fail validation collection: example.contacts2 doc: { _id:
ObjectId('5a2191ebacbbfc2bdc4dcffc'), name: "Amanda",
status: "Updated" }
Restrictions
You cannot specify a validator for collections in the admin, local,
and config databases.
You cannot specify a validator for system.* collections.
Update and delete
operations

Data Modeling

Summary:
Model Tree Structrue

Schema Validation
Thank You………
If you have any quries please write to [email protected]".

You might also like