SlideShare une entreprise Scribd logo
1  sur  66
Télécharger pour lire hors ligne
MongoDB Basics
M K Harischandra
What We Will Discuss
● Installing MongoDB
● Starting, Stopping and Restarting Mongod
● Starting and Using Mongo Shell Client
● MongoDB Document Structure
● Document Types in MongoDB
● MongoDB CRUD Operations
Installing MongoDB
● Two ways to install
○ Install as a service
(from Install MongoDB section in http://docs.mongodb.
org/manual/tutorial/install-mongodb-on-red-hat-centos-or-fedora-
linux/)
○ Download standalone editions from http://www.mongodb.
org/downloads
Starting/Stopping MongoDB Service
● Starting the Service
○ service mongod start
● Stop the Service
○ service mongod stop
● Restarting the Service
○ service mongod restart
Starting/Stopping MongoDB Standalone
Server
● Starting the Server
○ Run mongod in bin folder
● ./mongod --dbpath data/db (- the db location should be given)
● Stop the Server
○ killall mongod
● Starting the Mongo Shell command interface
○ Run mongo in bin folder
● ./mongo
○ By default, mongo looks for a database server listening on port 27017 on
the localhost interface
○ To connect to a server on a different port or interface, use the --port and
--host options
Starting Mongo Shell
● Some commands
○ db - Display the current db
○ show dbs - Display list of databases
○ use mydb - Switch the current db to mydb
○ show collections - Display the collections in the current db
Using Mongo Shell
● Insert Documents (Records)
○ Create two documents, named j and k
j = { name : "mongo" }
k = { x : 3 }
○ Insert documents
When we insert the first document into collection things, the mongod
will create both the mydb database and the things collection
db.things.insert( j )
db.things.insert( k )
○ Confirm that the collection named things exists
show collections
The mongo shell will return the list of the collections in the current (i.e.
mydb) database.
At this point, the only collection is things.
All mongod databases also have a system.indexes collection
Using Mongo Shell
● View Documents (Records)
○ Issuing a query on the things collection, using the find() method
db.things.find()
The result would be something like
{ "_id" : ObjectId("4c2209f9f3924d31102bd84a"), "name" : "mongo" }
{ "_id" : ObjectId("4c2209fef3924d31102bd84b"), "x" : 3 }
○ All MongoDB documents must have an _id field with a unique value
○ If operations do not explicitly specify a value for the _id field, mongo
creates a unique ObjectId value for the field before inserting it into the
collection.
ObjectId is a 12-byte BSON type, constructed using:
a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.
Using Mongo Shell
● Insert Multiple Documents (Records)
○ Insert multiple documents using for-loop
for (var i = 1; i <= 20; i++) db.things.insert( { x : 4 , j : i } )
The result would be something like
{ "_id" : ObjectId("51bef58140c59184a32e6400"), "x" : 4, "j" : 1 }
{ "_id" : ObjectId("51bef58140c59184a32e6401"), "x" : 4, "j" : 2 }
{ "_id" : ObjectId("51bef58140c59184a32e6402"), "x" : 4, "j" : 3 }
{ "_id" : ObjectId("51bef58140c59184a32e6403"), "x" : 4, "j" : 4 }
○ Query the collection
db.things.find()
The find() returns a cursor.
The mongo shell displays the first 20 documents in the collection.
To iterate the cursor and return more documents, use the it operation in
the mongo shell.
Using Mongo Shell
● Working with the Cursor
○ When query a collection, MongoDB returns a “cursor” object that
contains the results of the query.
○ The mongo shell then iterates over the cursor to display the results.
Rather than returning all results at once, the shell iterates over the
cursor 20 times to display the first 20 results and then waits for a
request to iterate over the remaining results.
○ Iterate over the Cursor with a Loop
var c = db.things.find() - c is the cursor variable
while ( c.hasNext() ) printjson( c.next() )
var c = db.things.find()
for (var i = 1; i <= 10; i++) printjson( c[i] )
Using Mongo Shell
● Using Array Operations with the Cursor
○ When the documents in a cursor are accessed using the array index
notation, mongo first calls the cursor.toArray() method and loads into
RAM all documents returned by the cursor.
○ This operation iterates the cursor completely and exhausts the cursor.
○ For very large result sets, mongo may run out of available memory.
Using Mongo Shell
● Query for Specific Documents (Filtering)
○ MongoDB has a rich query system that allows you to select and filter the
documents in a collection along specific fields and values.
● db.things.find( { name : "mongo" } )
Returns the documents where the name is mongo.
● Return a Single Document from a Collection
○ The findOne() method returns a single document from a MongoDB
collection.
● db.things.findOne()
Returns a single document.
● Limit the Number of Documents in the Result Set
○ Specify the maximum number of documents in the result set by calling
the limit() method on a cursor
● db.things.find().limit(3)
Using Mongo Shell
● The document structure
○ The document structure in MongoDB are BSON objects with support for
the full range of BSON types.
○ The structure would be something like
{
field1: value1,
field2: value2,
field3: value3,
...
fieldN: valueN
}
○ The value can be another document, an array, an array of documents as
well as the basic types such as Double, String, and Date
MongoDB Document Structure
● Sample document
var mydoc = {
_id: ObjectId("5099803df3f4948bd2f98391"),
name: { first: "Alan", last: "Turing" },
birth: new Date('Jun 23, 1912'),
death: new Date('Jun 07, 1954'),
contribs: [ "Turing machine", "Turing test", "Turingery" ],
views : NumberLong(1250000)
}
○ The document contains the following fields
● _id that holds an ObjectId.
● name that holds a subdocument that contains the fields first and last.
● birth and death, which both have Date types.
● contribs that holds an array of strings.
● views that holds a value of NumberLong type.
* Refer Mongo documentation for DB, Collection and Field name restrictions
MongoDB Document Structure
● Record Documents
○ Store data from users’ applications
○ Maximum BSON document size is 16 megabytes
○ Restrictions on field names
● The field name _id is reserved for use as a primary key; its value must
be unique in the collection, is immutable, and may be of any type
other than an array
● The field names cannot start with the $ character
● The field names cannot contain the . character
○ In documents, the _id field is always indexed for regular collections.
○ The _id field may contain values of any BSON data type other than an
array.
* Refer Mongo documentation for _id field guidance
Document Types in MongoDB
● Record Documents - Example
{
_id: 1,
name: { first: 'John', last: 'Backus' },
birth: new Date('Dec 03, 1924'),
death: new Date('Mar 17, 2007'),
contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ],
awards: [
{ award: 'National Medal of Science',
year: 1975,
by: 'National Science Foundation' },
{ award: 'Turing Award',
year: 1977,
by: 'ACM' }
]
}
Document Types in MongoDB
● Query Specification Documents
○ Query documents specify the conditions that determine which records to
select for read, update, and delete operations.
○ You can use <field>:<value> expressions to specify the equality condition
and query operator expressions to specify additional conditions.
db.bios.find( { _id: 1 } )
db.bios.remove( { _id: { $gt: 3 } } )
db.bios.update( { _id: 1, name: { first: 'John', last: 'Backus' } }, <update>,
<options> )
Document Types in MongoDB
● Update Specification Documents
○ Update documents specify the data modifications to perform during an
update() operation to modify existing records in a collection.
○ Update document example
{
$set: { 'name.middle': 'Warner' },
$push: { awards: { award: 'IBM Fellow', year: '1963', by: 'IBM' } }
}
○ Update method call
db.bios.update(
{ _id: 1 },
{
$set: { 'name.middle': 'Warner' },
$push: { awards: { award: 'IBM Fellow', year: '1963', by: 'IBM' } }
}
)
Document Types in MongoDB
● Index Specification Documents
○ Index specification documents describe the fields to index on during the
index creation.
○ Index document example
{ _id: 1, 'name.last': 1 }
This document specifies the multi-key index on the _id field and the last
field contained in the subdocument name field.
Value is either 1 for ascending or -1 for descending.
○ Index method call
db.bios.ensureIndex( { _id: 1, 'name.last': 1 } )
Document Types in MongoDB
● Sort Order Specification Documents
○ Sort order documents specify the order of documents that a query()
returns.
○ Sort order document example
{ 'name.last': 1, 'name.first': 1 }
This document specifies the sort order using the fields from a sub-
document name first sort by the last field ascending, then by the first
field also ascending.
Value is either 1 for ascending or -1 for descending.
○ Sort method call
db.bios.find().sort( { 'name.last': 1, 'name.first': 1 } )
Document Types in MongoDB
● The insert() Method
db.collection.insert( <document> )
○ Insert a Document Specifying an _id Field
db.bios.insert( { _id: 1,
name: { first: 'John', last: 'Backus' },
birth: new Date('Dec 03, 1924'),
death: new Date('Mar 17, 2007'),
contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ],
awards: [ { award: 'W.W. McDowell Award',
year: 1967,
by: 'IEEE Computer Society' },
{ award: 'National Medal of Science',
year: 1975,
by: 'National Science Foundation' },
{ award: 'Turing Award',
year: 1977,
by: 'ACM' },
{ award: 'Draper Prize',
year: 1993,
by: 'National Academy of Engineering' } ]
} )
MongoDB CRUD - Create
● The insert() Method
○ Insert a Document without Specifying an _id Field
If the new document does not contain an _id field, then the insert() method
adds the _id field to the document and generates a unique ObjectId for the
value.
db.bios.insert( {
name: { first: 'John', last: 'McCarthy' }, birth: new Date('Sep 04, 1927'),
death: new Date('Dec 24, 2011'),
contribs: [ 'Lisp', 'Artificial Intelligence', 'ALGOL' ],
awards: [ { award: 'Turing Award', year: 1971, by: 'ACM' },
{ award: 'Kyoto Prize', year: 1988, by: 'Inamori Foundation' },
{ award: 'National Medal of Science', year: 1990,
by: 'National Science Foundation' } ]
})
○ Bulk Insert Multiple Documents
If an array of documents passed, it'll performs a bulk insert into a collection.
MongoDB CRUD - Create
● The save() Method
db.collection.save( <document> )
db.bios.save( {
name: { first: 'Guido', last: 'van Rossum'},
birth: new Date('Jan 31, 1956'),
contribs: [ 'Python' ],
awards: [
{
award: 'Award for the Advancement of Free Software',
year: 2001,
by: 'Free Software Foundation'
},
{
award: 'NLUUG Award',
year: 2003,
by: 'NLUUG'
}
]
}
)
MongoDB CRUD - Create
● The update() Method(Upsert flag)
○ The update() operation in MongoDB accepts an “upsert” flag that modifies
the behavior of update() from updating existing documents, to inserting
data.
○ These update() operations with the upsert flag eliminate the need to
perform an additional operation to check for existence of a record before
performing either an update or an insert operation. These update
operations use the <query> argument to determine the write operation.
○ If the query matches an existing document(s), the operation is an update.
○ If the query matches no document in the collection, the operation is an
insert.
db.collection.update( <query>, <update>, { upsert: true } )
MongoDB CRUD - Create
● The update() Method(Upsert flag)
○ Insert a Document that Contains field and value Pairs.
If the <update> argument includes only field and value pairs, the new
document contains the fields and values specified in the <update>
argument.
If query does not include an _id field, the operation adds the _id field and
generates a unique ObjectId for its value.
db.bios.update({ name: { first: 'Dennis', last: 'Ritchie'} },
{
name: { first: 'Dennis', last: 'Ritchie'},
birth: new Date('Sep 09, 1941'),
death: new Date('Oct 12, 2011'),
contribs: [ 'UNIX', 'C' ],
awards: [{ award: 'Turing Award', year: 1983, by: 'ACM' },
{ award: 'National Medal of Technology', year: 1998, by: 'US'},
{ award: 'Japan Prize', year: 2011, by: 'The Japan Prize Foundation'}
]
}, { upsert: true } )
MongoDB CRUD - Create
● The update() Method(Upsert flag)
○ Insert a Document that Contains Update Operator Expressions.
If the <update> argument includes only update operators, the new document
contains the fields and values from <query> argument with the operations
from the <update> argument applied.
db.bios.update( { _id: 7, name: { first: 'Ken', last: 'Thompson' } },
{ $set: { birth: new Date('Feb 04, 1943'),
contribs: [ 'UNIX', 'C', 'B', 'UTF-8' ],
awards: [ { award: 'Turing Award', year: 1983, by: 'ACM' },
{ award: 'IEEE R. W. Hamming Medal', year: 1990, by: 'IEEE' },
{ award: 'National Medal of Technology', year: 1998, by: 'US' },
{ award: 'Tsutomu Kanai Award', year: 1999, by: 'IEEE' },
{ award: 'Japan Prize', year: 2011, by: 'The JPF' } ]
}
}, { upsert: true } )
MongoDB CRUD - Create
● The find() Method
○ The find() method is the primary method to select documents from a
collection.
○ It returns a cursor that contains a number of documents.
db.collection.find( <query>, <projection> )
● the <query> argument corresponds to the WHERE statement
● the <projection> argument corresponds to the list of fields to select
from the result set.
MongoDB CRUD - Read
● The find() Method
○ Return All Documents in a Collection
db.collection.find( )
- db.bios.find( { _id: 5 } )
○ Return Documents that Match Query Conditions
db.collection.find( <query> )
● Equality Matches
- db.bios.find( { _id: 5 } )
- db.bios.find(
{
_id : 10,
"name.first":"Ken"
}
)
MongoDB CRUD - Read
● Using operators
- db.bios.find(
{
_id: { $in: [ 5, 10 ] }
}
)
● Query for Ranges
- db.collection.find(
{
field: { $gt: value1, $lt: value2 }
}
)
- db.students.find( { score: { $gt: 0, $lt: 2 } } )
{ "_id" : 1, "score" : [ -1, 3 ] } - qualify
{ "_id" : 2, "score" : [ 1, 5 ] } - qualify
{ "_id" : 3, "score" : [ 5, 5 ] } - does not qualify
MongoDB CRUD - Read
Note: If the field contains an
array and the query has
multiple conditional operators,
the field as a whole will match
if either a single array element
meets the conditions or a
combination of array elements
meet the conditions.
● Query On Arrays
○ On an Array Element
The following operation returns a cursor to all documents in the
bios collection where the array field contribs contains the element
'UNIX'.
- db.bios.find( { contribs: 'UNIX' } )
○ Query Multiple Fields on an Array of Documents
The following operation returns a cursor to all documents in the
bios collection where awards array contains a subdocument
element that contains the award field equal to 'Turing Award' and
the year field greater than 1980.
- db.bios.find(
{ awards: {
$elemMatch: { award: 'Turing Award', year: { $gt: 1980 } }
}
}
)
MongoDB CRUD - Read
● On Subdocuments
○ Exact Matches
The following operation returns a cursor to all documents in the
bios collection where the subdocument name is exactly { first:
'Yukihiro', last: 'Matsumoto' }, including the order.
- db.bios.find( { name: { first: 'Yukihiro', last: 'Matsumoto' } } )
The name field must match the sub-document exactly, including
order.
The following will not be picked by this.
{ first: 'Yukihiro', aka: 'Matz', last: 'Matsumoto' }
{ last: 'Matsumoto', first: 'Yukihiro' }
MongoDB CRUD - Read
○ On Fields of a Subdocument
The following operation returns a cursor to all documents in the
bios collection where the subdocument name contains a field first
with the value 'Yukihiro' and a field last with the value
'Matsumoto'.
The query uses dot notation to access fields in a subdocument.
- db.bios.find( { 'name.first': 'Yukihiro', 'name.last': 'Matsumoto' } )
The query would match documents with name fields that held
either of the following.
{ first: 'Yukihiro', last: 'Matsumoto' }
{ first: 'Yukihiro', aka: 'Matz', last: 'Matsumoto' }
{ last: 'Matsumoto', first: 'Yukihiro' }
MongoDB CRUD - Read
● Logical Operators
○ OR Disjunctions
{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ]
}
The following operation returns a cursor to all documents in the
bios collection where either the field first in the sub-document
name starts with the letter G or where the field birth is less than
new Date('01/01/1945').
- db.bios.find(
{ $or: [ { 'name.first' : /^G/ },
{ birth: { $lt: new Date('01/01/1945') } }
]
}
)
MongoDB CRUD - Read
○ AND Conjunctions
{ $and: [{ <expression1> }, { <expression2> }, ... , { <expressionN> }]
}
The following operation returns a cursor to all documents in the
bios collection where the field first in the subdocument name
starts with the letter D and the array field contribs contains the
element UNIX.
- db.bios.find( { 'name.first': /^D/, contribs: 'UNIX' } )
- db.bios.find( {$and : [ { 'name.first': /^D/}, {contribs: 'UNIX' } ] } )
MongoDB CRUD - Read
○ NOT Operator
{ field: { $not: { <operator-expression> } } }
- db.inventory.find( { price: { $not: { $gt: 1.99 } } } )
- db.bios.find( {'name.first': { $not: /^D/}})
○ NOR Operator
{ $nor: [{ <expression1> }, { <expression2> }, ..., { <expressionN> }] }
- db.inventory.find( { $nor: [ { price: 1.99 },
{ qty: { $lt: 20 } },
{ sale: true }
]
} )
- db.bios.find( { $nor: [ {'name.first': /^G/}, {'name.first': /^D/} ] } )
MongoDB CRUD - Read
○ With a Projection
If there is a <projection> argument, the find() method returns only those
fields as specified in the <projection> argument to include or exclude.
Note: The _id field is implicitly included in the <projection> argument. In
projections that explicitly include fields, _id is the only field that you can
explicitly exclude. Otherwise, you cannot mix include field and exclude field
specifications.
db.collection.find( <query>, <projection> )
● Specify the Fields to Return
The following operation finds all documents in the bios collection and
returns only the name field, the contribs field, and the _id field.
- db.bios.find( { }, { name: 1, contribs: 1 } )
MongoDB CRUD - Read
● Explicitly Exclude the _id Field
The following operation finds all documents in the bios collection and
returns only the name field and the contribs field.
- db.bios.find( { }, { name: 1, contribs: 1, _id: 0 } )
● Return All but the Excluded Fields
The following operation finds the documents in the bios collection
where the contribs field contains the element 'OOP' and returns all fields
except the _id field, the first field in the name subdocument, and the
birth field from the matching documents.
- db.bios.find( { contribs: 'OOP' }, { _id: 0, 'name.first': 0, birth: 0 } )
● On Arrays and Subdocuments
The following operation finds all documents in the bios collection and
returns the last field in the name subdocument and the first two
elements in the contribs array.
- db.bios.find( { }, { _id: 0, 'name.last': 1, contribs: { $slice: 2 } } )
MongoDB CRUD - Read
○ Iterate the Returned Cursor
The find() method returns a cursor to the results. However, in the mongo
shell, if the returned cursor is not assigned to a variable, then the cursor is
automatically iterated up to 20 times to print up to the first 20 documents
that match the query.
- db.bios.find( { _id: 1 } );
● With Variable Name
When you assign the find() to a variable, you can type the name of the
cursor variable to iterate up to 20 times [1] and print the matching
documents.
- var myCursor = db.bios.find( { _id: 1 } );
myCursor
MongoDB CRUD - Read
● With next() Method
You can use the cursor method next() to access the documents.
- var myCursor = db.bios.find( { _id: 1 } );
var myDocument = myCursor.hasNext() ? myCursor.next() : null;
if (myDocument) {
var myName = myDocument.name;
print (tojson(myName));
}
To print, you can also use the printjson() method instead of
print(tojson()):
if (myDocument) {
var myName = myDocument.name;
printjson(myName);
}
MongoDB CRUD - Read
● With forEach() Method
You can use the cursor method forEach() to iterate the cursor and
access the documents.
var myCursor = db.bios.find( { _id: 1 } );
myCursor.forEach(printjson);
MongoDB CRUD - Read
○ Modify the Cursor Behavior
In addition to the <query> and the <projection> arguments, the mongo shell
and the drivers provide several cursor methods that you can call on the
cursor returned by find() method to modify its behavior.
● Order Documents in the Result Set
The sort() method orders the documents in the result set.
The following operation returns all documents (or more precisely, a
cursor to all documents) in the bios collection ordered by the name field
ascending:
db.bios.find().sort( { name: 1 } )
sort() corresponds to the ORDER BY statement in SQL.
MongoDB CRUD - Read
● Limit the Number of Documents to Return
The limit() method limits the number of documents in the result set.
The following operation returns at most 5 documents (or more
precisely, a cursor to at most 5 documents) in the bios collection:
db.bios.find().limit( 5 )
limit() corresponds to the LIMIT statement in SQL.
● Set the Starting Point of the Result Set
The skip() method controls the starting point of the results set.
The following operation returns all documents, skipping the first 5
documents in the bios collection:
db.bios.find().skip( 5 )
MongoDB CRUD - Read
● Combine Cursor Methods
You can chain these cursor methods, as in the following examples.
db.bios.find().sort( { name: 1 } ).limit( 5 )
db.bios.find().limit( 5 ).sort( { name: 1 } )
MongoDB CRUD - Read
● The findOne() Method
The findOne() method selects a single document from a collection and returns
that document. findOne() does not return a cursor.
The findOne() method has the following syntax.
db.collection.findOne( <query>, <projection> )
Except for the return value, findOne() method is quite similar to the find()
method; in fact, internally, the findOne() method is the find() method with a
limit of 1.
MongoDB CRUD - Read
○ With Empty Query Specification
If there is no <query> argument, the findOne() method selects just one
document from a collection.
The following operation returns a single document from the bios collection:
- db.bios.findOne()
○ With a Query Specification
If there is a <query> argument, the findOne() method selects the first
document from a collection that meets the <query> argument:
The following operation returns the first matching document from the bios
collection where either the field first in the subdocument name starts with
the letter G or where the field birth is less than new Date('01/01/1945'):
- db.bios.findOne( { $or: [ { 'name.first' : /^G/ },
{ birth: { $lt: new Date('01/01/1945') } } ]
})
MongoDB CRUD - Read
○ With a Projection
You can pass a <projection> argument to findOne() to control the fields
included in the result set.
● Specify the Fields to Return
The following operation finds a document in the bios collection and
returns only the name field, the contribs field, and the _id field.
- db.bios.findOne( { }, { name: 1, contribs: 1 } )
● Return All but the Excluded Fields
The following operation returns a document in the bios collection
where the contribs field contains the element OOP and returns all
fields except the _id field, the first field in the name subdocument, and
the birth field from the matching documents:
- db.bios.findOne( { contribs: 'OOP' }, { _id: 0, 'name.first': 0, birth: 0 }
)
MongoDB CRUD - Read
○ Access the findOne Result
Although similar to the find() method, because the findOne() method
returns a document rather than a cursor, you cannot apply the cursor
methods such as limit(), sort(), and skip() to the result of the findOne()
method. However, you can access the document directly, as in the
example:
- var myDocument = db.bios.findOne();
if (myDocument) {
var myName = myDocument.name;
print (tojson(myName));
}
MongoDB CRUD - Read
● The update() Method
○ The update() method is the primary method used to modify documents in
a MongoDB collection.
○ By default, the update() method updates a single document, but by using
the multi option, update() can update all documents that match the
query criteria in the collection.
○ The update() method can either replace the existing document with the
new document or update specific fields in the existing document.
- db.collection.update( <query>, <update>, <options> )
● the <query> argument corresponds to the WHERE statement, and
● the <update> corresponds to the SET ... statement.
MongoDB CRUD - Update
○ Modify with Update Operators
If the <update> argument contains only update operator expressions such
as the $set operator expression, the update() method updates the
corresponding fields in the document.
● Update a Field in a Document
Use $set to update a value of a field.
The following operation queries the bios collection for the first
document that has an _id field equal to 1 and sets the value of the field
middle, in the subdocument name, to Warner.
db.bios.update(
{ _id: 1 },
{ $set: { 'name.middle': 'Warner' },}
)
MongoDB CRUD - Update
● Add a New Field to a Document
The following operation queries the bios collection for the first
document that has an _id field equal to 3 and adds to that document a
new mbranch field and a new aka field in the subdocument name.
db.bios.update( { _id: 3 },
{ $set: { mbranch: 'Navy',
'name.aka': 'Amazing Grace' }
}
)
MongoDB CRUD - Update
● Remove a Field from a Document
If the <update> argument contains $unset operator, the update()
method removes the field from the document.
The following operation queries the bios collection for the first
document that has an _id field equal to 3 and removes the birth field
from the document.
db.bios.update( { _id: 3 },
{ $unset: { birth: 1 } }
)
MongoDB CRUD - Update
● Update Arrays
○ Update an Element by Specifying Its Position
If the update operation requires an update of an element in an
array field, the update() method can perform the update using
the position of the element and dot notation. Arrays in MongoDB
are zero-based.
The following operation queries the bios collection for the first
document with _id field equal to 1 and updates the second
element in the contribs array.
db.bios.update( { _id: 1 }, { $set: { 'contribs.1': 'ALGOL 58' } } )
MongoDB CRUD - Update
○ Update an Element without Specifying Its Position
The update() method can perform the update using the $
positional operator if the position is not known. The array field
must appear in the query argument in order to determine which
array element to update.
The following operation queries the bios collection for the first
document where the _id field equals 3 and the contribs array
contains an element equal to compiler. If found, the update()
method updates the first matching element in the array to A
compiler in the document:
db.bios.update( { _id: 3, 'contribs': 'compiler' },
{ $set: { 'contribs.$': 'A compiler' } } )
MongoDB CRUD - Update
○ Update a Document Element without Specifying Its Position
The update() method can perform the update of an array that
contains subdocuments by using the positional operator (i.e. $)
and the dot notation.
The following operation queries the bios collection for the first
document where the _id field equals 6 and the awards array
contains a subdocument element with the by field equal to ACM.
If found, the update() method updates the by field in the first
matching subdocument.
db.bios.update( { _id: 6, 'awards.by': 'ACM' } ,
{ $set: { 'awards.$.by': 'Association for
Computing Machinery' } }
)
MongoDB CRUD - Update
○ Add an Element to an Array
The following operation queries the bios collection for the first
document that has an _id field equal to 1 and adds a new element
to the awards field.
db.bios.update( { _id: 1 },
{ $push: { awards: { award: 'IBM Fellow', year:
1963, by: 'IBM' } }
}
)
MongoDB CRUD - Update
● Update Multiple Documents
If the <options> argument contains the multi option set to true or 1,
the update() method updates all documents that match the query.
The following operation queries the bios collection for all documents
where the awards field contains a subdocument element with the
award field equal to Turing and sets the turing field to true in the
matching documents.
db.bios.update( { 'awards.award': 'Turing' },
{ $set: { turing: true } },
{ multi: true }
)
MongoDB CRUD - Update
○ Replace Existing Document with New Document
If the <update> argument contains only field and value pairs, the update()
method replaces the existing document with the document in the <update>
argument, except for the _id field.
The following operation queries the bios collection for the first document
that has a name field equal to { first: 'John', last: 'McCarthy' } and replaces
all but the _id field in the document with the fields in the <update>
argument.
db.bios.update( { name: { first: 'John', last: 'McCarthy' } },
{ name: { first: 'Ken', last: 'Iverson' },
born: new Date('Dec 17, 1941'),
died: new Date('Oct 19, 2004'), contribs: [ 'APL', 'J' ],
awards: [ { award: 'Turing Award', year: 1979, by: 'ACM'
},
{ award: 'Harry H. Goode Memorial Award',
year: 1975, by: 'IEEE Computer Society' },
{ award: 'IBM Fellow', year: 1970, by: 'IBM' } ]
} )
MongoDB CRUD - Update
● The update() Operations with the upsert Flag
○ If you set the upsert option in the <options> argument to true or 1 and no
existing document match the <query> argument, the update() method can
insert a new document into the collection.
○ The following operation queries the bios collection for a document with
the _id field equal to 11 and the name field equal to { first: 'James', last:
'Gosling'}. If the query selects a document, the operation performs an
update operation. If a document is not found, update() inserts a new
document containing the fields and values from <query> argument with
the operations from the <update> argument applied.
MongoDB CRUD - Update
db.bios.update( { _id:11, name: { first: 'James', last: 'Gosling' } },
{ $set: { born: new Date('May 19, 1955'), contribs: [ 'Java' ],
awards: [{ award: 'The Economist Innovation Award',
year: 2002, by: 'The Economist' },
{ award: 'Officer of the Order of Canada',
year: 2007, by: 'Canada' } ]
}
}, { upsert: true }
)
MongoDB CRUD - Update
● The save() Method
○ The save() method performs a special type of update(), depending on the
_id field of the specified document.
db.collection.save( <document> )
○ Behavior
If you specify a document with an _id field, save() performs an update()
with the upsert option set: if an existing document in the collection has the
same _id, save() updates that document, and inserts the document
otherwise. If you do not specify a document with an _id field to save(),
performs an insert() operation.
That is, save() method is equivalent to the update() method with the
upsert option and a <query> argument with an _id field.
MongoDB CRUD - Update
○ Save Performs an Update
If the <document> argument contains the _id field that exists in the
collection, the save() method performs an update that replaces the
existing document with the <document> argument.
The following operation queries the bios collection for a document where
the _id equals ObjectId("507c4e138fada716c89d0014") and replaces the
document with the <document> argument.
db.bios.save( { _id: ObjectId("507c4e138fada716c89d0014"),
name: { first: 'Martin', last: 'Odersky' },
contribs: [ 'Scala' ] }
)
MongoDB CRUD - Update
● The remove() method
Use the remove() method to delete documents from a collection.
db.collection.remove( <query>, <justOne> )
The <query> argument corresponds to the WHERE statement, and
The <justOne> argument takes a Boolean and has the same effect as LIMIT 1.
remove() deletes documents from the collection. If you do not specify a query,
remove() removes all documents from a collection, but does not remove the
indexes.
MongoDB CRUD - Delete
○ Remove All Documents that Match a Condition
If there is a <query> argument, the remove() method deletes from the
collection all documents that match the argument.
The following operation deletes all documents from the bios collection
where the subdocument name contains a field first whose value starts
with G.
db.bios.remove( { 'name.first' : /^G/ } )
○ Remove a Single Document that Matches a Condition
If there is a <query> argument and you specify the <justOne> argument as
true or 1, remove() only deletes a single document from the collection that
matches the query.
The following operation deletes a single document from the bios
collection where the turing field equals true.
db.bios.remove( { turing: true }, 1 )
MongoDB CRUD - Delete
○ Remove All Documents from a Collection
If there is no <query> argument, the remove() method deletes all
documents from a collection. The following operation deletes all
documents from the bios collection.
db.bios.remove()
To remove all documents from a collection, it may be more efficient to use
the drop() method to drop the entire collection, including the indexes, and
then recreate the collection and rebuild the indexes.
MongoDB CRUD - Delete
MongoDB Basics
Thank You

Contenu connexe

Tendances (20)

Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
 
Connecting NodeJS & MongoDB
Connecting NodeJS & MongoDBConnecting NodeJS & MongoDB
Connecting NodeJS & MongoDB
 
Mongo DB Presentation
Mongo DB PresentationMongo DB Presentation
Mongo DB Presentation
 
MongoDB
MongoDBMongoDB
MongoDB
 
Mongo DB
Mongo DB Mongo DB
Mongo DB
 
MongoDB 101
MongoDB 101MongoDB 101
MongoDB 101
 
MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB
MongoDBMongoDB
MongoDB
 
Mongo db
Mongo dbMongo db
Mongo db
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB
 
Mongo db – document oriented database
Mongo db – document oriented databaseMongo db – document oriented database
Mongo db – document oriented database
 
MongoDB : The Definitive Guide
MongoDB : The Definitive GuideMongoDB : The Definitive Guide
MongoDB : The Definitive Guide
 
Mongo db workshop # 01
Mongo db workshop # 01Mongo db workshop # 01
Mongo db workshop # 01
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg Solutions
 
Mongodb introduction and_internal(simple)
Mongodb introduction and_internal(simple)Mongodb introduction and_internal(simple)
Mongodb introduction and_internal(simple)
 
MongoDB presentation
MongoDB presentationMongoDB presentation
MongoDB presentation
 
MongoDB
MongoDBMongoDB
MongoDB
 
PhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHPPhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHP
 

En vedette

Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDBAlex Sharp
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBRavi Teja
 
ConFoo - Migrating To Mongo Db
ConFoo - Migrating To Mongo DbConFoo - Migrating To Mongo Db
ConFoo - Migrating To Mongo DbContext.IO
 
Mongo db tutorials
Mongo db tutorialsMongo db tutorials
Mongo db tutorialsAnuj Jain
 
Administration (Eliot Horowitz)
Administration (Eliot Horowitz)Administration (Eliot Horowitz)
Administration (Eliot Horowitz)MongoSF
 
Shankar's mongo db presentation
Shankar's mongo db presentationShankar's mongo db presentation
Shankar's mongo db presentationShankar Kamble
 
When to Use MongoDB
When to Use MongoDBWhen to Use MongoDB
When to Use MongoDBMongoDB
 
NoSQL databases - An introduction
NoSQL databases - An introductionNoSQL databases - An introduction
NoSQL databases - An introductionPooyan Mehrparvar
 
Intro to NoSQL and MongoDB
Intro to NoSQL and MongoDBIntro to NoSQL and MongoDB
Intro to NoSQL and MongoDBDATAVERSITY
 
CI and CD with Jenkins
CI and CD with JenkinsCI and CD with Jenkins
CI and CD with JenkinsMartin Málek
 
IOT Based Home Automation using Raspberry Pi-3
IOT Based Home Automation using Raspberry Pi-3IOT Based Home Automation using Raspberry Pi-3
IOT Based Home Automation using Raspberry Pi-3Mohammad Qasim Malik
 

En vedette (20)

Mongo DB
Mongo DBMongo DB
Mongo DB
 
Dineo
DineoDineo
Dineo
 
Mongo db
Mongo dbMongo db
Mongo db
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
ConFoo - Migrating To Mongo Db
ConFoo - Migrating To Mongo DbConFoo - Migrating To Mongo Db
ConFoo - Migrating To Mongo Db
 
MongoDB crud
MongoDB crudMongoDB crud
MongoDB crud
 
Mongo db tutorials
Mongo db tutorialsMongo db tutorials
Mongo db tutorials
 
Administration (Eliot Horowitz)
Administration (Eliot Horowitz)Administration (Eliot Horowitz)
Administration (Eliot Horowitz)
 
MediaGlu and Mongo DB
MediaGlu and Mongo DBMediaGlu and Mongo DB
MediaGlu and Mongo DB
 
Shankar's mongo db presentation
Shankar's mongo db presentationShankar's mongo db presentation
Shankar's mongo db presentation
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
When to Use MongoDB
When to Use MongoDBWhen to Use MongoDB
When to Use MongoDB
 
NOSQL Overview
NOSQL OverviewNOSQL Overview
NOSQL Overview
 
NoSQL databases - An introduction
NoSQL databases - An introductionNoSQL databases - An introduction
NoSQL databases - An introduction
 
Intro to NoSQL and MongoDB
Intro to NoSQL and MongoDBIntro to NoSQL and MongoDB
Intro to NoSQL and MongoDB
 
NoSQL databases
NoSQL databasesNoSQL databases
NoSQL databases
 
CI and CD with Jenkins
CI and CD with JenkinsCI and CD with Jenkins
CI and CD with Jenkins
 
IOT Based Home Automation using Raspberry Pi-3
IOT Based Home Automation using Raspberry Pi-3IOT Based Home Automation using Raspberry Pi-3
IOT Based Home Automation using Raspberry Pi-3
 

Similaire à Mongo db basics

Similaire à Mongo db basics (20)

Introduction To MongoDB
Introduction To MongoDBIntroduction To MongoDB
Introduction To MongoDB
 
Simple MongoDB design for Rails apps
Simple MongoDB design for Rails appsSimple MongoDB design for Rails apps
Simple MongoDB design for Rails apps
 
Mongo indexes
Mongo indexesMongo indexes
Mongo indexes
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Getting Started with MongoDB
Getting Started with MongoDBGetting Started with MongoDB
Getting Started with MongoDB
 
Sekilas PHP + mongoDB
Sekilas PHP + mongoDBSekilas PHP + mongoDB
Sekilas PHP + mongoDB
 
Mongo db
Mongo dbMongo db
Mongo db
 
Mongodb Introduction
Mongodb IntroductionMongodb Introduction
Mongodb Introduction
 
UNIT-1 MongoDB.pptx
UNIT-1 MongoDB.pptxUNIT-1 MongoDB.pptx
UNIT-1 MongoDB.pptx
 
Mongodb By Vipin
Mongodb By VipinMongodb By Vipin
Mongodb By Vipin
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introduction
 
Mongo learning series
Mongo learning series Mongo learning series
Mongo learning series
 
mongo.pptx
mongo.pptxmongo.pptx
mongo.pptx
 
MongoDB_ppt.pptx
MongoDB_ppt.pptxMongoDB_ppt.pptx
MongoDB_ppt.pptx
 
Indexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleIndexing Strategies to Help You Scale
Indexing Strategies to Help You Scale
 
Mongo DB schema design patterns
Mongo DB schema design patternsMongo DB schema design patterns
Mongo DB schema design patterns
 
Mongo db
Mongo dbMongo db
Mongo db
 
Mongodb Introduction
Mongodb Introduction Mongodb Introduction
Mongodb Introduction
 
Mondodb
MondodbMondodb
Mondodb
 
3-Mongodb and Mapreduce Programming.pdf
3-Mongodb and Mapreduce Programming.pdf3-Mongodb and Mapreduce Programming.pdf
3-Mongodb and Mapreduce Programming.pdf
 

Dernier

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 

Dernier (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

Mongo db basics

  • 1. MongoDB Basics M K Harischandra
  • 2. What We Will Discuss ● Installing MongoDB ● Starting, Stopping and Restarting Mongod ● Starting and Using Mongo Shell Client ● MongoDB Document Structure ● Document Types in MongoDB ● MongoDB CRUD Operations
  • 3. Installing MongoDB ● Two ways to install ○ Install as a service (from Install MongoDB section in http://docs.mongodb. org/manual/tutorial/install-mongodb-on-red-hat-centos-or-fedora- linux/) ○ Download standalone editions from http://www.mongodb. org/downloads
  • 4. Starting/Stopping MongoDB Service ● Starting the Service ○ service mongod start ● Stop the Service ○ service mongod stop ● Restarting the Service ○ service mongod restart
  • 5. Starting/Stopping MongoDB Standalone Server ● Starting the Server ○ Run mongod in bin folder ● ./mongod --dbpath data/db (- the db location should be given) ● Stop the Server ○ killall mongod
  • 6. ● Starting the Mongo Shell command interface ○ Run mongo in bin folder ● ./mongo ○ By default, mongo looks for a database server listening on port 27017 on the localhost interface ○ To connect to a server on a different port or interface, use the --port and --host options Starting Mongo Shell
  • 7. ● Some commands ○ db - Display the current db ○ show dbs - Display list of databases ○ use mydb - Switch the current db to mydb ○ show collections - Display the collections in the current db Using Mongo Shell
  • 8. ● Insert Documents (Records) ○ Create two documents, named j and k j = { name : "mongo" } k = { x : 3 } ○ Insert documents When we insert the first document into collection things, the mongod will create both the mydb database and the things collection db.things.insert( j ) db.things.insert( k ) ○ Confirm that the collection named things exists show collections The mongo shell will return the list of the collections in the current (i.e. mydb) database. At this point, the only collection is things. All mongod databases also have a system.indexes collection Using Mongo Shell
  • 9. ● View Documents (Records) ○ Issuing a query on the things collection, using the find() method db.things.find() The result would be something like { "_id" : ObjectId("4c2209f9f3924d31102bd84a"), "name" : "mongo" } { "_id" : ObjectId("4c2209fef3924d31102bd84b"), "x" : 3 } ○ All MongoDB documents must have an _id field with a unique value ○ If operations do not explicitly specify a value for the _id field, mongo creates a unique ObjectId value for the field before inserting it into the collection. ObjectId is a 12-byte BSON type, constructed using: a 4-byte value representing the seconds since the Unix epoch, a 3-byte machine identifier, a 2-byte process id, and a 3-byte counter, starting with a random value. Using Mongo Shell
  • 10. ● Insert Multiple Documents (Records) ○ Insert multiple documents using for-loop for (var i = 1; i <= 20; i++) db.things.insert( { x : 4 , j : i } ) The result would be something like { "_id" : ObjectId("51bef58140c59184a32e6400"), "x" : 4, "j" : 1 } { "_id" : ObjectId("51bef58140c59184a32e6401"), "x" : 4, "j" : 2 } { "_id" : ObjectId("51bef58140c59184a32e6402"), "x" : 4, "j" : 3 } { "_id" : ObjectId("51bef58140c59184a32e6403"), "x" : 4, "j" : 4 } ○ Query the collection db.things.find() The find() returns a cursor. The mongo shell displays the first 20 documents in the collection. To iterate the cursor and return more documents, use the it operation in the mongo shell. Using Mongo Shell
  • 11. ● Working with the Cursor ○ When query a collection, MongoDB returns a “cursor” object that contains the results of the query. ○ The mongo shell then iterates over the cursor to display the results. Rather than returning all results at once, the shell iterates over the cursor 20 times to display the first 20 results and then waits for a request to iterate over the remaining results. ○ Iterate over the Cursor with a Loop var c = db.things.find() - c is the cursor variable while ( c.hasNext() ) printjson( c.next() ) var c = db.things.find() for (var i = 1; i <= 10; i++) printjson( c[i] ) Using Mongo Shell
  • 12. ● Using Array Operations with the Cursor ○ When the documents in a cursor are accessed using the array index notation, mongo first calls the cursor.toArray() method and loads into RAM all documents returned by the cursor. ○ This operation iterates the cursor completely and exhausts the cursor. ○ For very large result sets, mongo may run out of available memory. Using Mongo Shell
  • 13. ● Query for Specific Documents (Filtering) ○ MongoDB has a rich query system that allows you to select and filter the documents in a collection along specific fields and values. ● db.things.find( { name : "mongo" } ) Returns the documents where the name is mongo. ● Return a Single Document from a Collection ○ The findOne() method returns a single document from a MongoDB collection. ● db.things.findOne() Returns a single document. ● Limit the Number of Documents in the Result Set ○ Specify the maximum number of documents in the result set by calling the limit() method on a cursor ● db.things.find().limit(3) Using Mongo Shell
  • 14. ● The document structure ○ The document structure in MongoDB are BSON objects with support for the full range of BSON types. ○ The structure would be something like { field1: value1, field2: value2, field3: value3, ... fieldN: valueN } ○ The value can be another document, an array, an array of documents as well as the basic types such as Double, String, and Date MongoDB Document Structure
  • 15. ● Sample document var mydoc = { _id: ObjectId("5099803df3f4948bd2f98391"), name: { first: "Alan", last: "Turing" }, birth: new Date('Jun 23, 1912'), death: new Date('Jun 07, 1954'), contribs: [ "Turing machine", "Turing test", "Turingery" ], views : NumberLong(1250000) } ○ The document contains the following fields ● _id that holds an ObjectId. ● name that holds a subdocument that contains the fields first and last. ● birth and death, which both have Date types. ● contribs that holds an array of strings. ● views that holds a value of NumberLong type. * Refer Mongo documentation for DB, Collection and Field name restrictions MongoDB Document Structure
  • 16. ● Record Documents ○ Store data from users’ applications ○ Maximum BSON document size is 16 megabytes ○ Restrictions on field names ● The field name _id is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of any type other than an array ● The field names cannot start with the $ character ● The field names cannot contain the . character ○ In documents, the _id field is always indexed for regular collections. ○ The _id field may contain values of any BSON data type other than an array. * Refer Mongo documentation for _id field guidance Document Types in MongoDB
  • 17. ● Record Documents - Example { _id: 1, name: { first: 'John', last: 'Backus' }, birth: new Date('Dec 03, 1924'), death: new Date('Mar 17, 2007'), contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ], awards: [ { award: 'National Medal of Science', year: 1975, by: 'National Science Foundation' }, { award: 'Turing Award', year: 1977, by: 'ACM' } ] } Document Types in MongoDB
  • 18. ● Query Specification Documents ○ Query documents specify the conditions that determine which records to select for read, update, and delete operations. ○ You can use <field>:<value> expressions to specify the equality condition and query operator expressions to specify additional conditions. db.bios.find( { _id: 1 } ) db.bios.remove( { _id: { $gt: 3 } } ) db.bios.update( { _id: 1, name: { first: 'John', last: 'Backus' } }, <update>, <options> ) Document Types in MongoDB
  • 19. ● Update Specification Documents ○ Update documents specify the data modifications to perform during an update() operation to modify existing records in a collection. ○ Update document example { $set: { 'name.middle': 'Warner' }, $push: { awards: { award: 'IBM Fellow', year: '1963', by: 'IBM' } } } ○ Update method call db.bios.update( { _id: 1 }, { $set: { 'name.middle': 'Warner' }, $push: { awards: { award: 'IBM Fellow', year: '1963', by: 'IBM' } } } ) Document Types in MongoDB
  • 20. ● Index Specification Documents ○ Index specification documents describe the fields to index on during the index creation. ○ Index document example { _id: 1, 'name.last': 1 } This document specifies the multi-key index on the _id field and the last field contained in the subdocument name field. Value is either 1 for ascending or -1 for descending. ○ Index method call db.bios.ensureIndex( { _id: 1, 'name.last': 1 } ) Document Types in MongoDB
  • 21. ● Sort Order Specification Documents ○ Sort order documents specify the order of documents that a query() returns. ○ Sort order document example { 'name.last': 1, 'name.first': 1 } This document specifies the sort order using the fields from a sub- document name first sort by the last field ascending, then by the first field also ascending. Value is either 1 for ascending or -1 for descending. ○ Sort method call db.bios.find().sort( { 'name.last': 1, 'name.first': 1 } ) Document Types in MongoDB
  • 22. ● The insert() Method db.collection.insert( <document> ) ○ Insert a Document Specifying an _id Field db.bios.insert( { _id: 1, name: { first: 'John', last: 'Backus' }, birth: new Date('Dec 03, 1924'), death: new Date('Mar 17, 2007'), contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ], awards: [ { award: 'W.W. McDowell Award', year: 1967, by: 'IEEE Computer Society' }, { award: 'National Medal of Science', year: 1975, by: 'National Science Foundation' }, { award: 'Turing Award', year: 1977, by: 'ACM' }, { award: 'Draper Prize', year: 1993, by: 'National Academy of Engineering' } ] } ) MongoDB CRUD - Create
  • 23. ● The insert() Method ○ Insert a Document without Specifying an _id Field If the new document does not contain an _id field, then the insert() method adds the _id field to the document and generates a unique ObjectId for the value. db.bios.insert( { name: { first: 'John', last: 'McCarthy' }, birth: new Date('Sep 04, 1927'), death: new Date('Dec 24, 2011'), contribs: [ 'Lisp', 'Artificial Intelligence', 'ALGOL' ], awards: [ { award: 'Turing Award', year: 1971, by: 'ACM' }, { award: 'Kyoto Prize', year: 1988, by: 'Inamori Foundation' }, { award: 'National Medal of Science', year: 1990, by: 'National Science Foundation' } ] }) ○ Bulk Insert Multiple Documents If an array of documents passed, it'll performs a bulk insert into a collection. MongoDB CRUD - Create
  • 24. ● The save() Method db.collection.save( <document> ) db.bios.save( { name: { first: 'Guido', last: 'van Rossum'}, birth: new Date('Jan 31, 1956'), contribs: [ 'Python' ], awards: [ { award: 'Award for the Advancement of Free Software', year: 2001, by: 'Free Software Foundation' }, { award: 'NLUUG Award', year: 2003, by: 'NLUUG' } ] } ) MongoDB CRUD - Create
  • 25. ● The update() Method(Upsert flag) ○ The update() operation in MongoDB accepts an “upsert” flag that modifies the behavior of update() from updating existing documents, to inserting data. ○ These update() operations with the upsert flag eliminate the need to perform an additional operation to check for existence of a record before performing either an update or an insert operation. These update operations use the <query> argument to determine the write operation. ○ If the query matches an existing document(s), the operation is an update. ○ If the query matches no document in the collection, the operation is an insert. db.collection.update( <query>, <update>, { upsert: true } ) MongoDB CRUD - Create
  • 26. ● The update() Method(Upsert flag) ○ Insert a Document that Contains field and value Pairs. If the <update> argument includes only field and value pairs, the new document contains the fields and values specified in the <update> argument. If query does not include an _id field, the operation adds the _id field and generates a unique ObjectId for its value. db.bios.update({ name: { first: 'Dennis', last: 'Ritchie'} }, { name: { first: 'Dennis', last: 'Ritchie'}, birth: new Date('Sep 09, 1941'), death: new Date('Oct 12, 2011'), contribs: [ 'UNIX', 'C' ], awards: [{ award: 'Turing Award', year: 1983, by: 'ACM' }, { award: 'National Medal of Technology', year: 1998, by: 'US'}, { award: 'Japan Prize', year: 2011, by: 'The Japan Prize Foundation'} ] }, { upsert: true } ) MongoDB CRUD - Create
  • 27. ● The update() Method(Upsert flag) ○ Insert a Document that Contains Update Operator Expressions. If the <update> argument includes only update operators, the new document contains the fields and values from <query> argument with the operations from the <update> argument applied. db.bios.update( { _id: 7, name: { first: 'Ken', last: 'Thompson' } }, { $set: { birth: new Date('Feb 04, 1943'), contribs: [ 'UNIX', 'C', 'B', 'UTF-8' ], awards: [ { award: 'Turing Award', year: 1983, by: 'ACM' }, { award: 'IEEE R. W. Hamming Medal', year: 1990, by: 'IEEE' }, { award: 'National Medal of Technology', year: 1998, by: 'US' }, { award: 'Tsutomu Kanai Award', year: 1999, by: 'IEEE' }, { award: 'Japan Prize', year: 2011, by: 'The JPF' } ] } }, { upsert: true } ) MongoDB CRUD - Create
  • 28. ● The find() Method ○ The find() method is the primary method to select documents from a collection. ○ It returns a cursor that contains a number of documents. db.collection.find( <query>, <projection> ) ● the <query> argument corresponds to the WHERE statement ● the <projection> argument corresponds to the list of fields to select from the result set. MongoDB CRUD - Read
  • 29. ● The find() Method ○ Return All Documents in a Collection db.collection.find( ) - db.bios.find( { _id: 5 } ) ○ Return Documents that Match Query Conditions db.collection.find( <query> ) ● Equality Matches - db.bios.find( { _id: 5 } ) - db.bios.find( { _id : 10, "name.first":"Ken" } ) MongoDB CRUD - Read
  • 30. ● Using operators - db.bios.find( { _id: { $in: [ 5, 10 ] } } ) ● Query for Ranges - db.collection.find( { field: { $gt: value1, $lt: value2 } } ) - db.students.find( { score: { $gt: 0, $lt: 2 } } ) { "_id" : 1, "score" : [ -1, 3 ] } - qualify { "_id" : 2, "score" : [ 1, 5 ] } - qualify { "_id" : 3, "score" : [ 5, 5 ] } - does not qualify MongoDB CRUD - Read Note: If the field contains an array and the query has multiple conditional operators, the field as a whole will match if either a single array element meets the conditions or a combination of array elements meet the conditions.
  • 31. ● Query On Arrays ○ On an Array Element The following operation returns a cursor to all documents in the bios collection where the array field contribs contains the element 'UNIX'. - db.bios.find( { contribs: 'UNIX' } ) ○ Query Multiple Fields on an Array of Documents The following operation returns a cursor to all documents in the bios collection where awards array contains a subdocument element that contains the award field equal to 'Turing Award' and the year field greater than 1980. - db.bios.find( { awards: { $elemMatch: { award: 'Turing Award', year: { $gt: 1980 } } } } ) MongoDB CRUD - Read
  • 32. ● On Subdocuments ○ Exact Matches The following operation returns a cursor to all documents in the bios collection where the subdocument name is exactly { first: 'Yukihiro', last: 'Matsumoto' }, including the order. - db.bios.find( { name: { first: 'Yukihiro', last: 'Matsumoto' } } ) The name field must match the sub-document exactly, including order. The following will not be picked by this. { first: 'Yukihiro', aka: 'Matz', last: 'Matsumoto' } { last: 'Matsumoto', first: 'Yukihiro' } MongoDB CRUD - Read
  • 33. ○ On Fields of a Subdocument The following operation returns a cursor to all documents in the bios collection where the subdocument name contains a field first with the value 'Yukihiro' and a field last with the value 'Matsumoto'. The query uses dot notation to access fields in a subdocument. - db.bios.find( { 'name.first': 'Yukihiro', 'name.last': 'Matsumoto' } ) The query would match documents with name fields that held either of the following. { first: 'Yukihiro', last: 'Matsumoto' } { first: 'Yukihiro', aka: 'Matz', last: 'Matsumoto' } { last: 'Matsumoto', first: 'Yukihiro' } MongoDB CRUD - Read
  • 34. ● Logical Operators ○ OR Disjunctions { $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] } The following operation returns a cursor to all documents in the bios collection where either the field first in the sub-document name starts with the letter G or where the field birth is less than new Date('01/01/1945'). - db.bios.find( { $or: [ { 'name.first' : /^G/ }, { birth: { $lt: new Date('01/01/1945') } } ] } ) MongoDB CRUD - Read
  • 35. ○ AND Conjunctions { $and: [{ <expression1> }, { <expression2> }, ... , { <expressionN> }] } The following operation returns a cursor to all documents in the bios collection where the field first in the subdocument name starts with the letter D and the array field contribs contains the element UNIX. - db.bios.find( { 'name.first': /^D/, contribs: 'UNIX' } ) - db.bios.find( {$and : [ { 'name.first': /^D/}, {contribs: 'UNIX' } ] } ) MongoDB CRUD - Read
  • 36. ○ NOT Operator { field: { $not: { <operator-expression> } } } - db.inventory.find( { price: { $not: { $gt: 1.99 } } } ) - db.bios.find( {'name.first': { $not: /^D/}}) ○ NOR Operator { $nor: [{ <expression1> }, { <expression2> }, ..., { <expressionN> }] } - db.inventory.find( { $nor: [ { price: 1.99 }, { qty: { $lt: 20 } }, { sale: true } ] } ) - db.bios.find( { $nor: [ {'name.first': /^G/}, {'name.first': /^D/} ] } ) MongoDB CRUD - Read
  • 37. ○ With a Projection If there is a <projection> argument, the find() method returns only those fields as specified in the <projection> argument to include or exclude. Note: The _id field is implicitly included in the <projection> argument. In projections that explicitly include fields, _id is the only field that you can explicitly exclude. Otherwise, you cannot mix include field and exclude field specifications. db.collection.find( <query>, <projection> ) ● Specify the Fields to Return The following operation finds all documents in the bios collection and returns only the name field, the contribs field, and the _id field. - db.bios.find( { }, { name: 1, contribs: 1 } ) MongoDB CRUD - Read
  • 38. ● Explicitly Exclude the _id Field The following operation finds all documents in the bios collection and returns only the name field and the contribs field. - db.bios.find( { }, { name: 1, contribs: 1, _id: 0 } ) ● Return All but the Excluded Fields The following operation finds the documents in the bios collection where the contribs field contains the element 'OOP' and returns all fields except the _id field, the first field in the name subdocument, and the birth field from the matching documents. - db.bios.find( { contribs: 'OOP' }, { _id: 0, 'name.first': 0, birth: 0 } ) ● On Arrays and Subdocuments The following operation finds all documents in the bios collection and returns the last field in the name subdocument and the first two elements in the contribs array. - db.bios.find( { }, { _id: 0, 'name.last': 1, contribs: { $slice: 2 } } ) MongoDB CRUD - Read
  • 39. ○ Iterate the Returned Cursor The find() method returns a cursor to the results. However, in the mongo shell, if the returned cursor is not assigned to a variable, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents that match the query. - db.bios.find( { _id: 1 } ); ● With Variable Name When you assign the find() to a variable, you can type the name of the cursor variable to iterate up to 20 times [1] and print the matching documents. - var myCursor = db.bios.find( { _id: 1 } ); myCursor MongoDB CRUD - Read
  • 40. ● With next() Method You can use the cursor method next() to access the documents. - var myCursor = db.bios.find( { _id: 1 } ); var myDocument = myCursor.hasNext() ? myCursor.next() : null; if (myDocument) { var myName = myDocument.name; print (tojson(myName)); } To print, you can also use the printjson() method instead of print(tojson()): if (myDocument) { var myName = myDocument.name; printjson(myName); } MongoDB CRUD - Read
  • 41. ● With forEach() Method You can use the cursor method forEach() to iterate the cursor and access the documents. var myCursor = db.bios.find( { _id: 1 } ); myCursor.forEach(printjson); MongoDB CRUD - Read
  • 42. ○ Modify the Cursor Behavior In addition to the <query> and the <projection> arguments, the mongo shell and the drivers provide several cursor methods that you can call on the cursor returned by find() method to modify its behavior. ● Order Documents in the Result Set The sort() method orders the documents in the result set. The following operation returns all documents (or more precisely, a cursor to all documents) in the bios collection ordered by the name field ascending: db.bios.find().sort( { name: 1 } ) sort() corresponds to the ORDER BY statement in SQL. MongoDB CRUD - Read
  • 43. ● Limit the Number of Documents to Return The limit() method limits the number of documents in the result set. The following operation returns at most 5 documents (or more precisely, a cursor to at most 5 documents) in the bios collection: db.bios.find().limit( 5 ) limit() corresponds to the LIMIT statement in SQL. ● Set the Starting Point of the Result Set The skip() method controls the starting point of the results set. The following operation returns all documents, skipping the first 5 documents in the bios collection: db.bios.find().skip( 5 ) MongoDB CRUD - Read
  • 44. ● Combine Cursor Methods You can chain these cursor methods, as in the following examples. db.bios.find().sort( { name: 1 } ).limit( 5 ) db.bios.find().limit( 5 ).sort( { name: 1 } ) MongoDB CRUD - Read
  • 45. ● The findOne() Method The findOne() method selects a single document from a collection and returns that document. findOne() does not return a cursor. The findOne() method has the following syntax. db.collection.findOne( <query>, <projection> ) Except for the return value, findOne() method is quite similar to the find() method; in fact, internally, the findOne() method is the find() method with a limit of 1. MongoDB CRUD - Read
  • 46. ○ With Empty Query Specification If there is no <query> argument, the findOne() method selects just one document from a collection. The following operation returns a single document from the bios collection: - db.bios.findOne() ○ With a Query Specification If there is a <query> argument, the findOne() method selects the first document from a collection that meets the <query> argument: The following operation returns the first matching document from the bios collection where either the field first in the subdocument name starts with the letter G or where the field birth is less than new Date('01/01/1945'): - db.bios.findOne( { $or: [ { 'name.first' : /^G/ }, { birth: { $lt: new Date('01/01/1945') } } ] }) MongoDB CRUD - Read
  • 47. ○ With a Projection You can pass a <projection> argument to findOne() to control the fields included in the result set. ● Specify the Fields to Return The following operation finds a document in the bios collection and returns only the name field, the contribs field, and the _id field. - db.bios.findOne( { }, { name: 1, contribs: 1 } ) ● Return All but the Excluded Fields The following operation returns a document in the bios collection where the contribs field contains the element OOP and returns all fields except the _id field, the first field in the name subdocument, and the birth field from the matching documents: - db.bios.findOne( { contribs: 'OOP' }, { _id: 0, 'name.first': 0, birth: 0 } ) MongoDB CRUD - Read
  • 48. ○ Access the findOne Result Although similar to the find() method, because the findOne() method returns a document rather than a cursor, you cannot apply the cursor methods such as limit(), sort(), and skip() to the result of the findOne() method. However, you can access the document directly, as in the example: - var myDocument = db.bios.findOne(); if (myDocument) { var myName = myDocument.name; print (tojson(myName)); } MongoDB CRUD - Read
  • 49. ● The update() Method ○ The update() method is the primary method used to modify documents in a MongoDB collection. ○ By default, the update() method updates a single document, but by using the multi option, update() can update all documents that match the query criteria in the collection. ○ The update() method can either replace the existing document with the new document or update specific fields in the existing document. - db.collection.update( <query>, <update>, <options> ) ● the <query> argument corresponds to the WHERE statement, and ● the <update> corresponds to the SET ... statement. MongoDB CRUD - Update
  • 50. ○ Modify with Update Operators If the <update> argument contains only update operator expressions such as the $set operator expression, the update() method updates the corresponding fields in the document. ● Update a Field in a Document Use $set to update a value of a field. The following operation queries the bios collection for the first document that has an _id field equal to 1 and sets the value of the field middle, in the subdocument name, to Warner. db.bios.update( { _id: 1 }, { $set: { 'name.middle': 'Warner' },} ) MongoDB CRUD - Update
  • 51. ● Add a New Field to a Document The following operation queries the bios collection for the first document that has an _id field equal to 3 and adds to that document a new mbranch field and a new aka field in the subdocument name. db.bios.update( { _id: 3 }, { $set: { mbranch: 'Navy', 'name.aka': 'Amazing Grace' } } ) MongoDB CRUD - Update
  • 52. ● Remove a Field from a Document If the <update> argument contains $unset operator, the update() method removes the field from the document. The following operation queries the bios collection for the first document that has an _id field equal to 3 and removes the birth field from the document. db.bios.update( { _id: 3 }, { $unset: { birth: 1 } } ) MongoDB CRUD - Update
  • 53. ● Update Arrays ○ Update an Element by Specifying Its Position If the update operation requires an update of an element in an array field, the update() method can perform the update using the position of the element and dot notation. Arrays in MongoDB are zero-based. The following operation queries the bios collection for the first document with _id field equal to 1 and updates the second element in the contribs array. db.bios.update( { _id: 1 }, { $set: { 'contribs.1': 'ALGOL 58' } } ) MongoDB CRUD - Update
  • 54. ○ Update an Element without Specifying Its Position The update() method can perform the update using the $ positional operator if the position is not known. The array field must appear in the query argument in order to determine which array element to update. The following operation queries the bios collection for the first document where the _id field equals 3 and the contribs array contains an element equal to compiler. If found, the update() method updates the first matching element in the array to A compiler in the document: db.bios.update( { _id: 3, 'contribs': 'compiler' }, { $set: { 'contribs.$': 'A compiler' } } ) MongoDB CRUD - Update
  • 55. ○ Update a Document Element without Specifying Its Position The update() method can perform the update of an array that contains subdocuments by using the positional operator (i.e. $) and the dot notation. The following operation queries the bios collection for the first document where the _id field equals 6 and the awards array contains a subdocument element with the by field equal to ACM. If found, the update() method updates the by field in the first matching subdocument. db.bios.update( { _id: 6, 'awards.by': 'ACM' } , { $set: { 'awards.$.by': 'Association for Computing Machinery' } } ) MongoDB CRUD - Update
  • 56. ○ Add an Element to an Array The following operation queries the bios collection for the first document that has an _id field equal to 1 and adds a new element to the awards field. db.bios.update( { _id: 1 }, { $push: { awards: { award: 'IBM Fellow', year: 1963, by: 'IBM' } } } ) MongoDB CRUD - Update
  • 57. ● Update Multiple Documents If the <options> argument contains the multi option set to true or 1, the update() method updates all documents that match the query. The following operation queries the bios collection for all documents where the awards field contains a subdocument element with the award field equal to Turing and sets the turing field to true in the matching documents. db.bios.update( { 'awards.award': 'Turing' }, { $set: { turing: true } }, { multi: true } ) MongoDB CRUD - Update
  • 58. ○ Replace Existing Document with New Document If the <update> argument contains only field and value pairs, the update() method replaces the existing document with the document in the <update> argument, except for the _id field. The following operation queries the bios collection for the first document that has a name field equal to { first: 'John', last: 'McCarthy' } and replaces all but the _id field in the document with the fields in the <update> argument. db.bios.update( { name: { first: 'John', last: 'McCarthy' } }, { name: { first: 'Ken', last: 'Iverson' }, born: new Date('Dec 17, 1941'), died: new Date('Oct 19, 2004'), contribs: [ 'APL', 'J' ], awards: [ { award: 'Turing Award', year: 1979, by: 'ACM' }, { award: 'Harry H. Goode Memorial Award', year: 1975, by: 'IEEE Computer Society' }, { award: 'IBM Fellow', year: 1970, by: 'IBM' } ] } ) MongoDB CRUD - Update
  • 59. ● The update() Operations with the upsert Flag ○ If you set the upsert option in the <options> argument to true or 1 and no existing document match the <query> argument, the update() method can insert a new document into the collection. ○ The following operation queries the bios collection for a document with the _id field equal to 11 and the name field equal to { first: 'James', last: 'Gosling'}. If the query selects a document, the operation performs an update operation. If a document is not found, update() inserts a new document containing the fields and values from <query> argument with the operations from the <update> argument applied. MongoDB CRUD - Update
  • 60. db.bios.update( { _id:11, name: { first: 'James', last: 'Gosling' } }, { $set: { born: new Date('May 19, 1955'), contribs: [ 'Java' ], awards: [{ award: 'The Economist Innovation Award', year: 2002, by: 'The Economist' }, { award: 'Officer of the Order of Canada', year: 2007, by: 'Canada' } ] } }, { upsert: true } ) MongoDB CRUD - Update
  • 61. ● The save() Method ○ The save() method performs a special type of update(), depending on the _id field of the specified document. db.collection.save( <document> ) ○ Behavior If you specify a document with an _id field, save() performs an update() with the upsert option set: if an existing document in the collection has the same _id, save() updates that document, and inserts the document otherwise. If you do not specify a document with an _id field to save(), performs an insert() operation. That is, save() method is equivalent to the update() method with the upsert option and a <query> argument with an _id field. MongoDB CRUD - Update
  • 62. ○ Save Performs an Update If the <document> argument contains the _id field that exists in the collection, the save() method performs an update that replaces the existing document with the <document> argument. The following operation queries the bios collection for a document where the _id equals ObjectId("507c4e138fada716c89d0014") and replaces the document with the <document> argument. db.bios.save( { _id: ObjectId("507c4e138fada716c89d0014"), name: { first: 'Martin', last: 'Odersky' }, contribs: [ 'Scala' ] } ) MongoDB CRUD - Update
  • 63. ● The remove() method Use the remove() method to delete documents from a collection. db.collection.remove( <query>, <justOne> ) The <query> argument corresponds to the WHERE statement, and The <justOne> argument takes a Boolean and has the same effect as LIMIT 1. remove() deletes documents from the collection. If you do not specify a query, remove() removes all documents from a collection, but does not remove the indexes. MongoDB CRUD - Delete
  • 64. ○ Remove All Documents that Match a Condition If there is a <query> argument, the remove() method deletes from the collection all documents that match the argument. The following operation deletes all documents from the bios collection where the subdocument name contains a field first whose value starts with G. db.bios.remove( { 'name.first' : /^G/ } ) ○ Remove a Single Document that Matches a Condition If there is a <query> argument and you specify the <justOne> argument as true or 1, remove() only deletes a single document from the collection that matches the query. The following operation deletes a single document from the bios collection where the turing field equals true. db.bios.remove( { turing: true }, 1 ) MongoDB CRUD - Delete
  • 65. ○ Remove All Documents from a Collection If there is no <query> argument, the remove() method deletes all documents from a collection. The following operation deletes all documents from the bios collection. db.bios.remove() To remove all documents from a collection, it may be more efficient to use the drop() method to drop the entire collection, including the indexes, and then recreate the collection and rebuild the indexes. MongoDB CRUD - Delete