Mongo DB Documentation-2922'11
Mongo DB Documentation-2922'11
2
Mongo DB Documentation-2922'
Installation
Hello World.
"_id" : ObjectId("65af4d56fa0119335140f82d"),
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
Database Database
Table Collection
Select a particular database to access, e.g. mydb. This will create mydb if it does not already
exist:
use mydb;
4
Mongo DB Documentation-2922'
Chapter 2: Collections
Remarks.
Create Database
Examples
Create a Collection
5
Mongo DB Documentation-2922'
Examples
Create
6
Mongo DB Documentation-2922'
age: 27}])
Update
Delete
db.people.deleteOne({name: 'Tom'})
db.people.deleteMany({name: 'Tom'})
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'})
: 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:
The $pull operator is the opposite of $push, you can pull specific items from arrays.
The $pop operator allows you to remove the first or the last value from an array.
8
Mongo DB Documentation-2922'
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
db.students.update(
{ _id: 1, grades: 80 },
{ $set: { "grades.$" : 82 } }
)
9
Mongo DB Documentation-2922'
Examples
Aggregation is used to perform complex data search operations in the mongo query which c
an't be done in normal "find" query.
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:
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"}
}]
);
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.
db.employees.aggregate([
{$group:{"_id":"$dept"}}
]);
{ "_id" : "HR" }
{ "_id" : "Facilities" }
{ "_id" : "Admin" }
db.employees.aggregate([
{$group:{"_id":null, "totalAge":{$sum:"$age"}}
}]);
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'
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 }
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 }
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'
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 }.
‘$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"
}
}
15
Mongo DB Documentation-2922'
> 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
}
16
Mongo DB Documentation-2922'
db.students.find({firstName:"Prosen"});
{
"_id" : ObjectId("58f2547804951ad51ad206f5"),
"studentNo" : "1",
"firstName" : "Prosen",
"lastName" : "Ghosh",
"age" : "23"
}
AND Queries
db.students.find(
{
"firstName": "Prosen",
"age": { "$gte": 23 }
}
);
Output:
{
"_id" : ObjectId("58f29a694117d1b7af126dca"),
"studentNo" : 1,
"firstName" : "Prosen",
"lastName" : "Ghosh",
"age" : 25
}
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
}
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
}
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
}
20
Mongo DB Documentation-2922'
Inserts:
Insert Operation:
Syntax:
db.collectionName.insert(
{
field1: value1,
field2: value2,
// ... other fields
}
);
Upserts:
Upsert Operation:
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
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
22