Mongo DB Documentation-2922'
Chapter 1: Getting started with MongoDB
Chapter 2: Collections
Remarks.
Examples
Syntax
Examples
Chapter 3 : MongoDB Aggregation
Examples
Chapter 4: Upserts and Inserts
Inserts:
Upserts:
Chapter 5: Indexes
Syntax
Single field
Compound
Delete
2
Mongo DB Documentation-2922'
Chapter 1: Getting started with MongoDB
● Data in the world started to grow tremendously after mobile application came in the
market. This huge amount of data became almost impossible to handle with tradition
al relational databases - SQL. NoSQL databases are introduced to handle those data
where much more flexibility comes like variable number of columns for each data.
● MongoDB is one of the leading NoSQL databases. Each collection contains a numbe
r of JSON documents.
● There is no join operation in MongoDB prior to v.3.2
Installation
1 .Compass. The GUI for MongoDB.
2 . Studio 3T
Note: I have attached hyperlink for installing MongoDB UI for Windows
Hello World.
After installation process, the following lines should be entered in mongo
> db.world.insert({ "Message" : "Hello World!" });
> db.world.find()
O/P
{
"_id" : ObjectId("65af4d56fa0119335140f82d"),
"Message" : "Hello World!"
Explanation:
● In the first line, we have inserted a { key : value } paired document in the default data
base test and in the collection named world.
● In the second line we retrieve the data we have just inserted.
3
Mongo DB Documentation-2922'
Complementary Terms
SQL Terms MongoDB Terms
Database Database
Table Collection
Entity / Row Document
Column Key / Field
Table Join Embedded Documents
Primary Key Primary Key
Basic commands on mongo shell
Show all available databases:
show dbs;
Select a particular database to access, e.g. mydb. This will create mydb if it does not already
exist:
use mydb;
Show all collections in the database:
show collections;
Show all functions that can be used with the database:
db.mydb.help();
To check your currently selected database, use the command db
> db
db.dropDatabase() command is used to drop a existing database.
db.dropDatabase()
4
Mongo DB Documentation-2922'
Chapter 2: Collections
Remarks.
Create Database
Examples
Create a Collection
First Select Or Create a database
> use mydb
switched to db mydb
Using db.createCollection("yourCollectionName") method you can explicitly create Collection.
> db.createCollection("newCollection1")
{ "ok" : 1 }
Using show collections command see all collections in the database.
> show collections
newCollection1
5
Mongo DB Documentation-2922'
Chapter 3: CRUD Operation
Syntax
● insert(document or array of documents)
● insertOne( 'document', { writeConcern: 'document' } )
● insertMany( { [ document 1 , document 2, ... ] }, { writeConcern: document, orde
red: boolean } )
● find(query, projection)
● findOne(query, projection)
● update(query, update)
● updateOne( query, update, { upsert: boolean, writeConcern: document } )
● updateMany( query, update, { upsert: boolean, writeConcern: document } )
● replaceOne( query, replacement, { upsert: boolean, writeConcern: document }
)
● remove(query, justOne)
● findAndModify(query, sort, update, options[optional])
Examples
Create
db.people.insert({name: 'Tom', age: 28});
Two new methods to insert documents into a collection, in MongoDB 3.2.x:
insertOne to insert only one record:-
db.people.insertOne({name: 'Tom', age: 28});
insertMany to insert multiple records:-
db.people.insertMany([
{
name: 'Tom',
age: 28
},
{
name: 'John',
age: 25
},
{
name: 'Kathy',
6
Mongo DB Documentation-2922'
age: 27}])
Update
Update the entire object:
db.people.update({name: 'Tom'}, {age: 29, name: 'Tom'})
db.people.updateOne({name: 'Tom'},{age: 29, name: 'Tom'})
db.people.updateMany({name: 'Tom'},{age: 29, name: 'Tom'})
Or just update a single field of a document. In this case age:
db.people.update({name: 'Tom'}, {$set: {age: 29}})
We can also update multiple documents simultaneously
db.people.updateOne({name: 'Tom'},{$set:{age: 30})
db.people.updateMany({name: 'Tom'},{$set:{age: 30}})
Delete
Deletes all documents matching the query parameter:
db.people.deleteOne({name: 'Tom'})
db.people.deleteMany({name: 'Tom'})
db.people.remove({name: 'Tom'}, true)
DeprecationWarning: Collection.remove() is deprecated. Use deleteOne, deleteMany, findOneAndDel
ete, or bulkWrite.
Read
Query for all the docs in the people collection that have a name field with a value of 'T
om':
db.people.find({name: 'Tom'})
Or just the first one
: db.people.findOne({name: 'Tom'})
7
Mongo DB Documentation-2922'
We can also specify which fields to return by passing a field selection parameter. The followi
ng will exclude the _id field and only include the age field:
db.people.find({name: 'Tom'}, {_id: 0, age: 1})
More update operators
We can use other operators besides $set when updating a document.
The $push operator allows you to push a value into an array
db.people.update({name: 'Tom'}, {$push: {nicknames: 'Tommy'}})
// This adds the string 'Tommy' into the nicknames array in Tom's document.
The $pull operator is the opposite of $push, you can pull specific items from arrays.
db.people.update({name: 'Tom'}, {$pull: {nicknames: 'Tommy'}})
// This removes the string 'Tommy' from the nicknames array in Tom's document.
The $pop operator allows you to remove the first or the last value from an array.
db.people.update({name: 'Tom'}, {$pop: {siblings: -1}})
// This will remove the first value from the siblings array
db.people.update({name: 'Tom'}, {$pop: {siblings: 1}})
// This will remove the last value from the siblings array
Update of embedded documents.
For the following schema:
{name: 'Tom', age: 28, marks: [50, 60, 70]}
Update Tom's marks to 55 where marks are 50:
db.people.update({name: "Tom", marks: 50}, {"$set": {"marks.$": 55}})
For the following schema:
{
name: 'Tom',
age: 28,
marks:
[
{subject: "English", marks: 90},
{subject: "Maths", marks: 100},
{subject: "Computes", marks: 20}
]
}
8
Mongo DB Documentation-2922'
Update Tom's English marks to 85 :
Db.people.update
(
{name: "Tom", "marks.subject": "English"},
{"$set":{"marks.$.marks": 85}}
)
Explaining above example:
By using {name: "Tom", "marks.subject": "English"} you will get the position of the object in t
he marks array, where subject is English. In "marks.$.marks", $ is used to update in that posi
tion of the marks array
Update Values in an Array
Consider a collection students with the following documents:
{ "_id" : 1, "grades" : [ 80, 85, 90 ] }
{ "_id" : 2, "grades" : [ 88, 90, 92 ] }
{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
To update 80 to 82 in the grades array in the first document
db.students.update(
{ _id: 1, grades: 80 },
{ $set: { "grades.$" : 82 } }
)
9
Mongo DB Documentation-2922'
Chapter 3 : MongoDB Aggregation
Examples
Aggregation is used to perform complex data search operations in the mongo query which c
an't be done in normal "find" query.
Create some dummy data:
db.employees.insert(
{
"name":"Adma",
"dept":"Admin",
"Languages":["german","french","english","hindi"],
"Age":30,
"totalExp":10
}
);
db.employees.insert(
{
"name":"Anna",
"dept":"Admin",
"Languages":["english","hindi"],
"Age":35,
"totalExp":11
}
);
db.employees.insert(
{"name":"Bob",
"dept":"Facilities",
"Languages":["english","hindi"],
"Age":36,
"totalExp":14
}
);
db.employees.insert(
{"name":"Cathy",
"dept":"Facilities",
"Languages":["hindi"],
"Age":31,
10
Mongo DB Documentation-2922'
"totalExp":4}
);
db.employees.insert(
{"name":"Mike",
"dept":"HR",
"languages":["english", "hindi", "spanish"],
"Age":26,
"totalExp":3}
);
db.employees.insert(
{"name":"Jenny",
"dept":"HR",
"languages":["english", "hindi", "spanish"],
"Age":25,
"totalExp":3}
);
Examples by topic:
1. Match: Used to match documents (like SQL where clause)
In MongoDB's aggregation framework, the $match stage is used to filter and select docume
nts that match specific criteria. It is similar to the find() method for queries but is used within
an aggregation pipeline to filter documents at an early stage in the processing.
db.employees.aggregate(
[{
$match:{dept:"Admin"}
}]
);
2. Project: Used to populate specific field's value(s)
In MongoDB, the term "projection" refers to the process of limiting the fields that are returned
in the result set of a query. It allows you to specify which fields you want to include or exclud
e in the output.
db.employees.aggregate(
[
{$match:{dept:"Admin"}},
{$project:{"name":1, "dept":1}}
]
);
11
Mongo DB Documentation-2922'
db.employees.aggregate(
{$project: {'_id':0, 'name': 1}}
)
Output:
{ "name" : "Adma" }
{ "name" : "Anna" }
{ "name" : "Bob" }
{ "name" : "Cathy" }
{ "name" : "Mike" }
{ "name" : "Jenny" }
3. Group: $group is used to group documents by specific field, here documents are groupe
d by "dept" field's value.
In MongoDB's aggregation framework, the $group stage is used to group documents by a sp
ecified expression and perform aggregate operations on the grouped data.
db.employees.aggregate([
{$group:{"_id":"$dept"}}
]);
{ "_id" : "HR" }
{ "_id" : "Facilities" }
{ "_id" : "Admin" }
db.employees.aggregate([
{$group:{"_id":null, "totalAge":{$sum:"$age"}}
}]);
{ "_id" : null, "noOfEmployee" : 183 }
4. Sum: $sum is used to count or sum the values inside a group.
db.employees.aggregate(
[{$group:{"_id":"$dept",
"noOfDept":{$sum:1}}
}]);
Output:
{ "_id" : "HR", "noOfDept" : 2 }
{ "_id" : "Facilities", "noOfDept" : 2 }
{ "_id" : "Admin", "noOfDept" : 2 }
12
Mongo DB Documentation-2922'
5. Average: Calculates average of specific field's value per group.
db.employees.aggregate([
{$group:{"_id":"$dept", "noOfEmployee":{$sum:1},
"avgExp":{$avg:"$totalExp"}}
}]);
Output:
{ "_id" : "HR", "noOfEmployee" : 2, "totalExp" : 3 }
{ "_id" : "Facilities", "noOfEmployee" : 2, "totalExp" : 9 }
{ "_id" : "Admin", "noOfEmployee" : 2, "totalExp" : 10.5 }
6. Minimum: Finds minimum value of a field in each group.
db.employees.aggregate([
{$group:{"_id":"$dept", "noOfEmployee":{$sum:1},
"minExp":{$min:"$totalExp"}}}
]);
Output:
{ "_id" : "HR", "noOfEmployee" : 2, "totalExp" : 3 }
{ "_id" : "Facilities", "noOfEmployee" : 2, "totalExp" : 4 }
{ "_id" : "Admin", "noOfEmployee" : 2, "totalExp" : 10 }
7. Maximum: Finds maximum value of a field in each group.
db.employees.aggregate(
[
{$group:{"_id":"$dept", "noOfEmployee":{$sum:1},
"maxExp":{$max:"$totalExp"}}}
]);
Output:
{ "_id" : "HR", "noOfEmployee" : 2, "totalExp" : 3 }
{ "_id" : "Facilities", "noOfEmployee" : 2, "totalExp" : 14 }
{ "_id" : "Admin", "noOfEmployee" : 2, "totalExp" : 11 }
8. Getting specific field's value from first and last document of each group:
db.employees.aggregate([
{$group:{"_id":"$age", "lasts":{$last:"$name"},
"firsts":{$first:"$name"}}}
]);
Output:
13
Mongo DB Documentation-2922'
{ "_id" : 25, "lasts" : "Jenny", "firsts" : "Jenny" }
{ "_id" : 26, "lasts" : "Mike", "firsts" : "Mike" }
{ "_id" : 35, "lasts" : "Cathy", "firsts" : "Anna" }
{ "_id" : 30, "lasts" : "Adma", "firsts" : "Adma" }
9. Minumum with maximum:
db.employees.aggregate([
{$group:{"_id":"$dept", "noOfEmployee":{$sum:1},
"maxExp":{$max:"$totalExp"},
"minExp":{$min: "$totalExp"}}
}]);
Output:
{ "_id" : "HR", "noOfEmployee" : 2, "maxExp" : 3, "minExp" : 3 }
{ "_id" : "Facilities", "noOfEmployee" : 2, "maxExp" : 14, "minExp" : 4 }
{ "_id" : "Admin", "noOfEmployee" : 2, "maxExp" : 11, "minExp" : 10 }
10. Push and addToSet: Push adds a field's value form each document in group to an array
used to project data in array format, addToSet is simlar to push but it omits duplicate values.
db.employees.aggregate([
{$group:{"_id":"dept", "arrPush":{$push:"$age"},
"arrSet": {$addToSet:"$age"}}}
]);
Output:
{ "_id" : "dept",
"arrPush" : [ 30, 35, 35, 35, 26, 25 ],
"arrSet" : [ 25, 26, 35, 30 ] }
11. Unwind: Used to create multiple in-memory documents for each value in the specified ar
ray type field, then we can do further aggregation based on those values.
db.employees.aggregate([
{$match:{"name":"Adma"}},
{$unwind:"$languages"}]);
Output:
{ "_id" : ObjectId("54982fac2e9b4b54ec384a0d"),
"name" : "Adma",
"dept" : "HR",
"languages" : "german",
"age" : 30,
"totalExp" : 10 }
{ "_id" : ObjectId("54982fac2e9b4b54ec384a0d"),
"name" : "Adma",
14
Mongo DB Documentation-2922'
"dept" : "HR",
"languages" : "french",
"age" : 30,
"totalExp" : 10 }
{ "_id" : ObjectId("54982fac2e9b4b54ec384a0d"),
"name" : "Adma",
"dept" : "HR",
"languages" : "english",
"age" : 30,
"totalExp" : 10 }
{ "_id" : ObjectId("54982fac2e9b4b54ec384a0d"),
"name" : "Adma",
"dept" : "HR",
"languages" : "hindi",
"age" : 30, "totalExp" : 10 }.
Left Outer Join with aggregation ( $Lookup)
‘$Lookup’ is an mongo db aggregation pipelines stage that performs a left outer join to anoth
er collection in the same database.
Syntax:
{
$lookup: {
from: "targetCollection",
localField: "localField",
foreignField: "foreignField",
as: "outputArray"
}
}
● ‘from’ : Specifies the base collection that you want to join.
● ‘localField’:Specifies the field from the input documents.
● ‘foriegnField’:Specifies the field from the target location.
● ‘as’:Specifies the name of the new array that will contain the joined documents.
15
Mongo DB Documentation-2922'
Query Document - Using AND, OR and IN Conditions
> db.students.find()
{
"_id" : ObjectId("58f29a694117d1b7af126dca"),
"studentNo" : 1,
"firstName" : "Prosen",
"lastName" : "Ghosh",
"age" : 25 }
{
"_id" : ObjectId("58f29a694117d1b7af126dcb"),
"studentNo" : 2,
"firstName" : "Rajib",
"lastName" : "Ghosh",
"age" : 25
}
{ "_id" : ObjectId("58f29a694117d1b7af126dcc"),
"studentNo" : 3,
"firstName" : "Rizve",
"lastName" : "Amin",
"age" : 23
}
{ "_id" : ObjectId("58f29a694117d1b7af126dcd"),
"studentNo" : 4,
"firstName" : "Jabed",
"lastName" : "Bangali",
"age" : 25
}
{
"_id" : ObjectId("58f29a694117d1b7af126dce"),
"studentNo" : 5,
"firstName" : "Gm",
"lastName" : "Anik",
"age" : 23
}
Similar mySql Query of the above command.
SELECT * FROM STUDENTS;
16
Mongo DB Documentation-2922'
db.students.find({firstName:"Prosen"});
{
"_id" : ObjectId("58f2547804951ad51ad206f5"),
"studentNo" : "1",
"firstName" : "Prosen",
"lastName" : "Ghosh",
"age" : "23"
}
Similar mySql Query of the above command.
SELECT * FROM students WHERE firstName = "Prosen";
AND Queries
db.students.find(
{
"firstName": "Prosen",
"age": { "$gte": 23 }
}
);
Output:
{
"_id" : ObjectId("58f29a694117d1b7af126dca"),
"studentNo" : 1,
"firstName" : "Prosen",
"lastName" : "Ghosh",
"age" : 25
}
Similar mySql Query of the above command.
SELECT * FROM students WHERE firstName = "Prosen" AND age >= 23
Or Queries
db.students.find(
{ "$or": [{
"firstName": "Prosen"
},
{ "age": {
"$gte": 23
}
}]
});
17
Mongo DB Documentation-2922'
{
"_id" : ObjectId("58f29a694117d1b7af126dca"),
"studentNo" : 1,
"firstName" : "Prosen",
"lastName" : "Ghosh",
"age" : 25
}
{ "_id" : ObjectId("58f29a694117d1b7af126dcb"),
"studentNo" : 2,
"firstName" : "Rajib",
"lastName" : "Ghosh",
"age" : 25
}
{ "_id" : ObjectId("58f29a694117d1b7af126dcc"),
"studentNo" : 3,
"firstName" : "Rizve",
"lastName" : "Amin",
"age" : 23
}
{ "_id" : ObjectId("58f29a694117d1b7af126dcd"),
"studentNo" : 4,
"firstName" : "Jabed",
"lastName" : "Bangali",
"age" : 25
}
{ "_id" : ObjectId("58f29a694117d1b7af126dce"),
"studentNo" : 5,
"firstName" : "Gm",
"lastName" : "Anik",
"age" : 23
}
Similar mySql Query of the above command.
SELECT * FROM students WHERE firstName = "Prosen" OR age >= 23
18
Mongo DB Documentation-2922'
And OR Queries
db.students.find(
{
firstName : "Prosen",
$or : [ {age : 23},
{age : 25}
]
}
);
{
"_id" : ObjectId("58f29a694117d1b7af126dca"),
"studentNo" : 1,
"firstName" : "Prosen",
"lastName" : "Ghosh",
"age" : 25
}
Similar mySql Query of the above command.
SELECT * FROM students WHERE firstName = "Prosen" AND age = 23 OR age = 25;
IN Queries
This queries can improve multiple use of OR Queries
db.students.find(
lastName:
{
$in:["Ghosh", "Amin"]
}
)
{ "_id" : ObjectId("58f29a694117d1b7af126dca"),
"studentNo" : 1,
"firstName" : "Prosen",
"lastName" : "Ghosh",
"age" : 25
}
{ "_id" : ObjectId("58f29a694117d1b7af126dcb"),
"studentNo" : 2,
"firstName" : "Rajib",
"lastName" : "Ghosh",
"age" : 25
19
Mongo DB Documentation-2922'
{ "_id" : ObjectId("58f29a694117d1b7af126dcc"),
"studentNo" : 3,
"firstName" : "Rizve",
"lastName" : "Amin",
"age" : 23
}
Similar mySql query to above command
select * from students where lastName in ('Ghosh', 'Amin')
20
Mongo DB Documentation-2922'
Chapter 4: Upserts and Inserts
In MongoDB, upserts and inserts refer to operations related to adding or updating doc
uments in a collection.
Inserts:
Insert Operation:
● An insert operation is used to add new documents to a collection.
● If the specified _id field in the document is not provided, MongoDB will automatically
generate a unique identifier for the document.
Syntax:
db.collectionName.insert(
{
field1: value1,
field2: value2,
// ... other fields
}
);
Upserts:
Upsert Operation:
● An upsert is a combination of "update" and "insert."
● It performs an update operation, but if no document matches the specified crit
eria, it inserts a new document.
● The term "upsert" is derived from "update" + "insert."
Syntax:
db.collectionName.update(
{ _id: "documentId" }, // Criteria to find the document
{
$set: {
field1: value1,
field2: value2,
// ... other fields
}
},
{ upsert: true } // Perform an upsert
);
21
Mongo DB Documentation-2922'
Chapter 5: Indexes
● In MongoDB, indexes are data structures that improve the speed of data retrieval ope
rations on a collection.
● They provide a way to efficiently locate and access documents based on the values o
f one or more fields.
● mongo can traverse the index in both directions.
Syntax
db.collection.createIndex({ field1: 1, field2: -1, ... })
Disadvantages:
Performance Impact:The indexes improve read performance, but can have a bad impact on
write performance, as inserting a document requires updating all indexes.
Examples
Single field
db.people.createIndex({name: 1})
This creates an ascending single field index on the field name.
Compound
db.people.createIndex({name: 1, age: -1})
This creates an index on multiple fields, in this case on the name and age fields. It will be as
cending in name and descending in age.
Reverse sorting is supported on any prefix of a compound index.
Delete
To drop an index you could use the index name
db.people.dropIndex("nameIndex")
Or
the index specification document
db.people.dropIndex({name: 1})
22