Web Development Using Angular JS and MONGO
Unit 5
Document with different types of values i)Document with Scalar Values ii)Document with Documents as values iii)Document with Array as values CRUD operation :Insert Operation i)insertOne() and ii)insertMany() with examples Perform Query Operation for the following situations i)Query on nested documents ii)Query an array ii)Query an array of nested documents iv)Geospatial Queries Query Operation Examples Update Operation: updateOne(), updateMany() replaceOne(), findAndModify() Update operation :Examples
Lab :Working with CRUD operations
Insert and Query Delete Operation: deleteMany(), deleteOne() iii)findOneAndDelete() Delete operation Examples Operation on Mongodb Data: projection Limiting Records Sorting Records Indexes in Mongodb, default _id index Creating and Index createIndex method Single Field, Compound, Multikey Geospatial,text Index, Hashed Index
Lab :Working with CRUD operations
Update and Delete Properties of Index i)Unique Indexes ii)Partial Indexes iii)Sparse Indexes iv)TTL Indexes Aggregation in Mongodb: i)aggregate() method Aggregate expressions: i) $sum ii) $avg iii) $min iv) $max v) $push vi) $addToSet vii) $first viii) $last Mongodb Backup: Export/Import data backup using shell i)mongodump ii)mongorestore Mongodb Backup: Export/Import data backup using Mongo Compass Monitoring Deployment using Mongodb: i)mongostat, mongotop
iii)serverStatus, dbStats, collStats
Lab: i)Creating different types of indexes ii)Aggregate data using different Aggregate expressions iii)Perform Mongodb data Export and Import using shell as well as mongo compass. iv)Working with mongo deployment commands
Understanding MongoDB Documents
3
{
field1: value1,
field2: value2,
field3: value3,
...
fieldN: valueN
}
Document with different types of values
4
Document with different types of values
5
CRUD��Create, Read, Update, Delete
Create Operations
7
Create or Insert operations
8
Inserting Data
9
db.myCollection.insertOne(
{
"name": "navindu", "age": 22
}
)
db.myCollection.insertMany([
{ "name": "navindu", "age": 22 },
{ "name": "kavindu", "age": 20 },
{ "name": "john doe", "age": 25}
])
>db. myCollection.insert({"location": "colombo" }),
WriteResult({ "nInserted" : 1 })
Insert a Single Document
10
db.inventory.find( { item: "canvas" } )
Insert Multiple Documents
11
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])
Insert Behavior
12
Read / Query Operations
13
The find() Method
14
>db.COLLECTION_NAME.find()
> db.mycol.find()
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", }
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "title" : "NoSQL Database", "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-09T21:05:00Z“)} ]
}
The pretty() Method
15
>db.COLLECTION_NAME.find().pretty()
> db.mycol.find().pretty()
{
"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
"title" : "MongoDB Overview",
}
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"),
"title" : "NoSQL Database",
"comments" :
[
{ "user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-09T21:05:00Z“)
}
]
}
The findOne() method
16
>db.COLLECTIONNAME.findOne()
> db.mycol.findOne({title: " NoSQL Database "})
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"),
"title" : "NoSQL Database",
"comments" :
[
{ "user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-09T21:05:00Z“)
}
]
}
RDBMS Where Clause Equivalents in MongoDB
17
Operation | Syntax | Example | RDBMS Equivalent |
Equality | {<key>:{$eg;<value>}} | db.mycol.find({"by":"tutorials point"}).pretty() | where by = 'tutorials point' |
Less Than | {<key>:{$lt:<value>}} | db.mycol.find({"likes":{$lt:50}}).pretty() | where likes < 50 |
Less Than Equals | {<key>:{$lte:<value>}} | db.mycol.find({"likes":{$lte:50}}).pretty() | where likes <= 50 |
Greater Than | {<key>:{$gt:<value>}} | db.mycol.find({"likes":{$gt:50}}).pretty() | where likes > 50 |
Greater Than Equals | {<key>:{$gte:<value>}} | db.mycol.find({"likes":{$gte:50}}).pretty() | where likes >= 50 |
Not Equals | {<key>:{$ne:<value>}} | db.mycol.find({"likes":{$ne:50}}).pretty() | where likes != 50 |
Values in an array | {<key>:{$in:[<value1>, <value2>,……<valueN>]}} | db.mycol.find({"name":{$in:["Raj", "Ram", "Raghu"]}}).pretty() | Where name matches any of the value in :["Raj", "Ram", "Raghu"] |
Values not in an array | {<key>:{$nin:<value>}} | db.mycol.find({"name":{$nin:["Ramu", "Raghav"]}}).pretty() | Where name values is not in the array :["Ramu", "Raghav"] or, doesn’t exist at all |
AND, OR, NOR, NOT Operation
18
>db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ] })
>db.mycol.find({ $or: [ {<key1>:<value1>}, { <key2>:<value2>} ] })
>db.mycol.find({ $not: [ {<key1>:<value1>}, { <key2>:<value2>} ] })
>db.mycol.find({ $nor: [ {<key1>:<value1>}, { <key2>:<value2>} ] })
>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"}, {"title": "MongoDB Overview"}]}).pretty()
'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')'
Perform Query Operation for the following situations
19
db.inventory.insertMany( [
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ 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" }
]);
Perform Query Operation for the following situations
20
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
db.inventory.find( { "size.uom": "in" } )
db.inventory.insertMany( [
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ 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" }
]);
Perform Query Operation for the following situations
21
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);
Query an Array for an Element
db.inventory.find( { tags: { $all: ["red", "blank"] } } )
db.inventory.find( { dim_cm: { $gt: 25 } } )
Query an Array with Compound Filter Conditions on the Array Elements
db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )
Query for an Array Element that Meets Multiple Criteria
db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )
Perform Query Operation for the following situations
22
db.inventory.insertMany( [
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
Query for a Document Nested in an Array
db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )
db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )
Specify a Query Condition on a Field in an Array of Documents
db.inventory.find( { 'instock.qty': { $lte: 20 } } )
Use the Array Index to Query for a Field in the Embedded Document
db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )
A Single Nested Document Meets Multiple Query Conditions on Nested Fields
db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )
db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )
Perform Query Operation for the following situations
23
<field>: { type: <GeoJSON type> , coordinates: <coordinates> }
location: {
type: "Point",
coordinates: [-73.856077, 40.848447]
}
Legacy Coordinate Pairs
Specify via an array
<field>: [ <x>, <y> ]
<field>: [<longitude>, <latitude> ]
Specify via an embedded document:
<field>: { <field1>: <x>, <field2>: <y> }
<field>: { <field1>: <longitude>, <field2>: <latitude> }
Update Operations
24
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
updateOne() method
25
>db.COLLECTION_NAME.updateOne(<filter>, <update>)
> db.empDetails.updateOne(
{First_Name: 'Radhika'},
{ $set: { Age: '30',e_mail: 'radhika_newemail@gmail.com'}}
)
{
"acknowledged" : true,
"matchedCount" : 1,
"modifiedCount" : 0 } >
updateMany() method
26
>db.COLLECTION_NAME.updateMany(<filter>, <update>)
> db.empDetails.updateMany(
{Age:{ $gt: "25" }},
{ $set: { Age: '00'}}
)
{
"acknowledged" : true,
"matchedCount" : 2,
"modifiedCount" : 2
}
replaceOne() method
27
> db.collection.replaceOne(filter, replacement, options)
db.collection.replaceOne(
<filter>,
<replacement>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
hint: <document|string>
}
)
findAndModify() method
28
> db.collection.findAndModify(document)
db.people.findAndModify(
{
query: { name: "Andy" },
update: { $inc: { score: 1 } },
upsert: true
}
)
Delete Operations
29
deleteOne() method
30
> db.collection.deleteOne(filter, option)
db.products.insertMany([
{ "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate": ISODate("2011-05-14"), "spec" : { "ram" : 4, "screen" : 6.5, "cpu" : 2.66 },"color":["white","black"],"storage":[64,128,256]},
{ "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512]},
{ "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128]},
{ "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate": ISODate("2020-05-14"),"spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256,1024]},
{ "_id" : 5, "name" : "SmartPhone", "price" : 599,"releaseDate": ISODate("2022-09-14"), "spec" : { "ram" : 4, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256]}
])
Using the deleteOne() method to delete a single document
db.products.deleteOne({_id: 1}) { "acknowledged" : true, "deletedCount" : 1 }
Using the deleteOne() method to delete the first document from a collection
db.products.deleteOne({}) { "acknowledged" : true, "deletedCount" : 1 }
deleteMany() method
31
> db.collection.deleteMany(filter, option)
db.products.insertMany([
{ "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate": ISODate("2011-05-14"), "spec" : { "ram" : 4, "screen" : 6.5, "cpu" : 2.66 },"color":["white","black"],"storage":[64,128,256]},
{ "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512]},
{ "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128]},
{ "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate": ISODate("2020-05-14"),"spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256,1024]},
{ "_id" : 5, "name" : "SmartPhone", "price" : 599,"releaseDate": ISODate("2022-09-14"), "spec" : { "ram" : 4, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256]}
])
Using the deleteMany() method to delete multiple documents
db.products.deleteMany({ price: 899 }) { "acknowledged" : true, "deletedCount" : 2 }
Using the deleteMany() method to delete all documents
db.products.deleteMany({})
findOneAndDelete() method
32
> db.collection.findOneAndDelete(filter, option)
db.pets.insertMany([
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 }
{ "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 }
{ "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 }
{ "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 }
{ "_id" : 5, "name" : "Bruce", "type" : "Bat", "weight" : 3 }
{ "_id" : 6, "name" : "Fetch", "type" : "Dog", "specs" : { "height" : 400, "weight" : 15, "color" : "brown" } }
{ "_id" : 7, "name" : "Jake", "type" : "Dog", "awards" : [ "Top Dog", "Best Dog", "Biggest Dog" ] }
db.pets.findOneAndDelete( { "type": "Cat" } )
Result
{ "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 }
db.pets.find()
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 } { "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 } { "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 } { "_id" : 5, "name" : "Bruce", "type" : "Bat", "weight" : 3 } { "_id" : 6, "name" : "Fetch", "type" : "Dog", "specs" : { "height" : 400, "weight" : 15, "color" : "brown" } } { "_id" : 7, "name" : "Jake", "type" : "Dog", "awards" : [ "Top Dog", "Best Dog", "Biggest Dog" ] }
Projection
33
>db.COLLECTION_NAME.find({},{KEY:1})
> db.products.find({price: 899});
db.products.insertMany([
{ "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate": ISODate("2011-05-14"), "spec" : { "ram" : 4, "screen" : 6.5, "cpu" : 2.66 },"color":["white","black"],"storage":[64,128,256]},
{ "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512]},
{ "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128]},
{ "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate": ISODate("2020-05-14"),"spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256,1024]},
{ "_id" : 5, "name" : "SmartPhone", "price" : 599,"releaseDate": ISODate("2022-09-14"), "spec" : { "ram" : 4, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256]}
])
Projection
34
> db.products.find({price: 899});
{ "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512]},
{ "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128]},
> db.products.find({}, {
name: 1,
price: 1
});
{ "_id" : 1, "name" : "xPhone", "price" : 799 }
{ "_id" : 2, "name" : "xTablet", "price" : 899 }
{ "_id" : 3, "name" : "SmartTablet", "price" : 899 }
{ "_id" : 4, "name" : "SmartPad", "price" : 699 }
{ "_id" : 5, "name" : "SmartPhone", "price" : 599 }
> db.products.find({}, {
name: 1,
price: 1
,
_id: 0
});
{ "name" : "xPhone", "price" : 799 }
{ "name" : "xTablet", "price" : 899 }
{ "name" : "SmartTablet", "price" : 899 }
{ "name" : "SmartPad", "price" : 699 }
{ "name" : "SmartPhone", "price" : 599 }
Projection
35
> db.products.find({_id:1}, {
releaseDate: 0,
spec: 0,
storage: 0
}).pretty()
{
"_id" : 1,
"name" : "xPhone",
"price" : 799,
"color" : [
"white",
"black"
],
"inventory" : [
{
"qty" : 1200,
"warehouse" : "San Jose"
}
]
}
Projection
36
> db.products.find({_id:1}, {
name: 1,
price: 1,
"spec.screen": 1
}).pretty()
{
"_id" : 1,
"name" : "xPhone",
"price" : 799,
"spec" : {
"screen" : 6.5
}
}
MongoDB 4.4
> db.products.find({_id:1}, {
name: 1,
price: 1,
spec : { screen: 1
}
}).pretty()
Projection
37
> db.products.find({}, {
name: 1,
"inventory.qty": 1
});
{ "_id" : 1, "name" : "xPhone", "inventory" : [ { "qty" : 1200 } ] }
{ "_id" : 2, "name" : "xTablet", "inventory" : [ { "qty" : 300 } ] }
{ "_id" : 3, "name" : "SmartTablet", "inventory" : [ { "qty" : 400 }, { "qty" : 200 } ] }
{ "_id" : 4, "name" : "SmartPad", "inventory" : [ { "qty" : 1200 } ] }
{ "_id" : 5, "name" : "SmartPhone" }
Limiting Records
38
>db.COLLECTION_NAME.find().limit(NUMBER)
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
>db.mycol.find({},{"title":1,_id:0}).limit(2)
Display only two documents while querying the document.
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
>
Sorting Records
39
>db.COLLECTION_NAME.find().sort({KEY:1})
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Tutorials Point Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>
Indexes in Mongodb
40
>db.COLLECTION_NAME.createIndex({KEY:1})
>db.mycol.createIndex({"title":1})
{ "createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
>
Indexes in Mongodb
41
>db.COLLECTION_NAME.dropIndex({KEY:1})
> db.mycol.dropIndex({"title":1})
{
“ok" : 0,
"errmsg" : "can't find index with key: { title: 1.0 }",
"code" : 27, "codeName" :
"IndexNotFound"
}
Indexes in Mongodb
42
>db.COLLECTION_NAME.dropIndexes()
> db.mycol.createIndex({"title":1,"description":-1})
>db.mycol.dropIndexes({"title":1,"description":-1})
{ "nIndexesWas" : 2,
"ok" : 1 } >
43