MongoDB¶
MongoDB does not require explicit creation. If you try to access something that doesnโt exist, MongoDB will create it for you.
Install¶
- Install
MongoDB Community
- Install
mongosh
(shell)
Vocabulary¶
Relational | MongoDB |
---|---|
Database | Database |
Table | Collection |
Column | Key |
Row | Document |
Index | Index |
Join | $lookup |
Foreign Key | Reference |
Data Format¶
BSON (Binary JSON): very similar to json
Mongosh¶
DDL¶
DML¶
Create¶
db.users.insertOne({
name: "Ahmed"
})
db.users.insertMany([
{
name: "Ahmed"
},
{
name: "Thahir"
}
])
Read¶
Find functions¶
Count¶
Update¶
$set
db.users.updateOne(
{
age: 26
},
{
$set: {age: 27}
}
)
db.users.updateMany(
{
age: 26
},
{
$set: {age: 27}
}
)
$set
$inc
$rename: {name: "Ahmed"}
$unset: {name: ""} // removes key; doesn't set to null
$push: {hobbies: "Swimming"} // adding to array key
$pull: {hobbies: "Swimming"} // remove from array key
Replace¶
db.users.replaceOne(
{
age: 26
},
{
name: "Thahir"
}
)
db.users.replace(
{
age: 26
},
{
name: "Thahir"
}
)
Delete¶
Filtering¶
// filter Thahir and return only name and age
db.users.find(
{
name: "Thahir"
},
{
name: 1,
age:1,
_id: 0
}
)
Complex Filters¶
{$eq: "Thahir"}
{$ne: "Thahir"}
{$gte: 10}
{$in: [
"Ahmed",
"Thahir",
5
]}
{$nin: [
"Ahmed",
"Thahir",
5
]}
{$exists: true} // only checks if key exists; hence includes documents with null
{$exists: false}
Filter Operations¶
// not
{
not: [
{filter_1: "enset"}
]
}
// and
{
filter_1: "enset",
filter_2: "enset"
}
{
$and: [
{filter_1: "enset"},
{filter_2: "enset"}
]
}
// or
{
$or: [
{filter_1: "enset"},
{filter_2: "enset"}
]
}