Unit - 5 - Chapter 3 - Creating, Updating, and Deleting Documents in MongoDB
Unit - 5 - Chapter 3 - Creating, Updating, and Deleting Documents in MongoDB
AND
DELETING DOCUMENTS
Objectives
• This
chapter covers the basics of moving data in and out of the
database, including the following:
• Adding new documents to a collection
• Removing documents from a collection
• Updating existing documents
• Choosing the correct level of safety versus speed for all of these
operations
Inserting and Saving Documents
• insert()
• It is the basic method for adding data to MongoDB.
• To insert a document into a collection
• If the collection does not exist, then this method will create the collection
• If the document does not specify an _id field, then MongoDB will add the _id field
and assign a unique ObjectId for the document before inserting.
• Most drivers create an ObjectId and insert the _id field, but the mongod will
create and populate the _id if the driver or application does not.
• If the document contains an _id field, the _id value must be unique within the
collection to avoid duplicate key error.
• Eg:
db.bios.insert({“age”: 23})
This will add an _id key to the document if it does not exist and stores into the
MongoDB
db.products.insert( { item: "card", qty: 15 } )
During the insert, mongod will create the _id field and assign it a unique
ObjectId value, as verified by the inserted document as shown below:
• These minimal checks also mean that it is fairly easy to insert invalid data
• Thus, you should only allow trusted sources, such as your application servers,
to connect to the database.
• All of the drivers for major languages do check for a variety of invalid data
(documents that are too large, contain non-UTF-8 strings, or use unrecognized
types) before sending anything to the database.
SAMPLE 100 YEAR
WEATHER
MONITORING DATA
Sample Results data
Sample movies collection data
Consider the following code:
>db.mycol.insert({ • Identify the collection
name
_id: ObjectId(7df78ad8902c),
• If the collection does not
title: 'MongoDB Overview', exist then what does the
description: 'MongoDB is no sql database', Mongo do?
by: 'tutorials point', • What happens if we do
not specify the id?
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
})
• To insert multiple documents in a single query, you can pass an array of documents in insert() command.
>db.post.insert([
{
title: 'MongoDB Overview', description: 'MongoDB is no sql database', by: 'tutorials point', url:
'http://www.tutorialspoint.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 },
{
title: 'NoSQL Database', description: "NoSQL database doesn't have tables", by: 'tutorials point',
url: http://www.tutorialspoint.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 20,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])
• Saving the document
• To insert the document you can use db.post.save(document) also.
• If you don't specify _id in the document then save() method will work
same as insert() method.
• If you specify _id then it will replace whole data of document containing _id
as specified in save() method.
Removing Documents
• > db.bios.remove()
• This will remove all of the documents in the bios collection.
• This doesn’t actually remove the collection, and any meta information about it
will still exist.
• The remove function optionally takes a query document as a parameter.
• When it’s given, only documents that match the criteria will be removed.
• Suppose, for instance, that we want to remove everyone from the mailing.list collection
where the value for "opt-out “is true:
• > db.mailing.list.remove({"opt-out" : true})
• Syntax
• In the find() method, if you pass multiple keys by separating them by ',' then
MongoDB treats it as AND condition.
• Following is the basic syntax of AND −
• >db.mycol.find({ $and: [ {key1: value1}, {key2:value2} ] } ).pretty()
OR in MongoDB
• Syntax
• To query documents based on the OR condition, you need to use $or keyword.
Following is the basic syntax of OR −
• >db.mycol.find( { $or: [ {key1: value1}, {key2:value2} ] } ).pretty()
• Query
• Find all the books written by “Cristina” and whose title is “MongoDB : A definitive guide”
• db.books.find({$and:[
{"by":“Cristina"},
{"title": " MongoDB : A definitive guide "}
]}).pretty()
• You can pass any number of key, value pairs in find clause
• Find all the books with the title “MongoDB Overview” or written by “Cristina”
• db.books.find({$or:[{"by":“Cristina"},
{"title": " MongoDB : A definitive guide "}]}).pretty()
• Find all the documents that have download greater than 10 and whose title is either MongoDB : A
definitive guide ' or written by ‘Cristina’
• db.books.find({“downloads": {$gt:500}, $or: [{"by": “Cristina"}, {"title": " MongoDB : A
definitive guide"}]}).pretty()
Updating Documents
• Once a document is stored in the database, it can be changed using the update
method.
• The update takes two parameters:
• a query document, which locates documents to update
• a modifier document, which describes the changes to make to the
documents found.
• Updating a document is atomic:
• if two updates happen at the same time, whichever one reaches the server first will be
applied, and then the next one will be applied.
• Thus, conflicting updates can safely be sent in rapid-fire succession without any
documents being corrupted: the last update will “win.”
• Consider the inventory collection shown below:
• db.inventory.insertMany( [
• { item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
• { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
• { item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
• { item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
• { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
• { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
• { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
• { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
• { item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
• { item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" } ] );
• Now let us work with update operator
• Update Documents in a Collection
"sex" : "male",
"location" : "Wisconsin",
}
• Now if joe decides that he actually enjoys a different book, "$set" can be used
again to change the value:
• > db.users.update({"name" : "joe"},
• ... {"$set" : {"favorite book" : "Green Eggs and Ham"}})
• Now if our fickle joe decides that he actually likes quite a few books,
he can change the value of the “favorite book” key into an array:
• > db.users.update({"name" : "joe"},
• ... {"$set" : {"favorite book" :
• ... ["Cat's Cradle", "Foundation Trilogy", "Ender's Game"]}})
$unset
• Now if joe realizes that he actually doesn’t like reading, he can remove the key
altogether with "$unset":
• > db.users.update({"name" : "joe"},
• ... {"$unset" : {"favorite book" : 1}})
• Now the document will be the same as it was at the beginning of this example without
the field favorite book
$set to change embedded documents
• You can also use "$set" to reach in and change
embedded documents:
> db.blog.posts.findOne()
> db.blog.posts.findOne()
{
{
"_id" :
"_id" : ObjectId("4b253b067525f35f94b60a31"), ObjectId("4b253b067525f35f94b60a31"),
"title" : "A Blog Post", "title" : "A Blog Post",
"content" : "...", "content" : "...",
"author" : {
"author" : {
"name" : "joe",
"email" : "[email protected]" "name" : "joe schmoe",
} "email" : "[email protected]"
} }