Optimization
Index
- Query get ke database adalah proses yang sangat resource consuming, terutama jika tabel memiliki data yang sangat banyak. Database perlu melakukan query satu per satu pada setiap row-nya
- Database index adalah collection of pointers, di mana tiap pointer merujuk pada sebuah full data record yang dijadikan acuan
- Saat kita mencari sebuah data dari database, kita akan mencari ke index terlebih dahulu. Ingat seharusnya index tidak berukuran sama atau lebih besar daripada database/tabel itu sendiri. Program akan menemukan indeks yang paling mendekati ke data yang kita cari, lalu database tinggal mencari memakai linear search biasa dimulai dari data yang ditunjuk pointer indeks tersebut
Application
SQL vs MongoDB
| Aspect | MySQL | MongoDB | | —————– | ———————————————————————————————– | ————————————————————————————————————————————————————————— | | Bentuk | Tabel | Document | | Acronym | Standard query language | Humongouos database (bisa menyimpan data berukuran sangat besar) | | Formatting | Schema, karena setiap Row akan memiliki format data dan kolom yang sama | JSON, karena object based | | Style | Rigid, karena formatnya sudah hardcoded dan sudah didefinisikan schemanya | Fleksibel | | Data format | Row-based | BSON, JSON yang dikonversi ke binary via Mongo driver | | Struktur komponen | Sebuah database terdiri dari kumpulan tabel, dan sebuah tabel terdiri dari kumpulan row | Sebuah database terdiri dari kumpulan collection (ekuivalen dengan table), dan setiap collection terdiri dari kumpulan dokumen/BSON document (ekuivalen dengan row) |
SQL
PostgreSQL
Instalasi
- Arch
yay -S postgresqlinitdb -D /var/lib/postgres/data
Data type
| Data type | Name in PostgreSQL | Description |
|---|---|---|
| UUID | uuid |
Basic Syntax
- Connect to Psql shell
psql
- Show/list databases
\l
- Switch between databases
\c database_name
- Lists /show tables/relations
\dt
NoSQL
MongoDB
Instalasi
- Arch
yay -S mongodb
- Windows
Basic syntax
- Connect to Mongo shell
mongosh- Starting from here, use mongo shell
- Show/list databases
show dbs
- Switch between database
use {database_name}
- Show/list collections
show collections
- Create database
use {non-existing_database_name}- NOTE: database empty ga bakal muncul saat
show dbs
- Delete/drop database
db.dropDatabase()
- Create collection
db.createCollection("{nama_collection}")
- Delete collection
db.dropCollection("{nama_collection}")
- Insert one data to collection
db.collectionName.insertOne({ name: "John", age: 29, gpa: 3.2 })- Berhasil: acknowledged = true
- Insert many data to collection
db.collectionName.insertMany([{ name: "John", age: 29, gpa: 3.2 }, { name: "Alice", age: 29, gpa: 2.8 } ]) - Select all data from collection
db.{collection_name}.find()
- Select data from collection with condition
- Syntax:
db.collectionName.find({condition}, {projection}) - Equality condition:
db.collectionName.find({ fieldName: "value" }); - Multiple condition (AND):
db.collectionName.find({ field1: "value1", field2: "value2" }); - Non-equality condition (misal di sini greater than, dilambangkan
$gt, artinya price yang lebih besar dari 100):db.collectionName.find({ price: { $gt: 100 } }); - OR condition (pakai tag `$or):
db.collectionName.find({ $or: [{ status: "active" }, { quantity: { $lt: 10 } }] }); - Select specific fields:
db.collectionName.find( { fieldName: "value" }, { fieldToInclude: 1, _id: 0 } ); // Includes 'fieldToInclude', excludes '_id' // Other format db.collectionName.find( { fieldName: "value" }, { fieldToInclude: true, _id: false } ); - By default
_idsudah pasti masuk, jadi kalau mau di-exclude harus dispesifikkan_id = 0
- Syntax:
- Select data with limit and sort
- Sort
db.collectionName.find().sort({name: -1}) // dari rendah ke tinggi (menaik, ascending) - Limit
db.collectionName.find().limit(5)
- Sort
- Update one data
- Syntax:
db.collectionName.updateOne({condition/filter}, {update}) - Contoh:
db.students.updateOne( {name: "Spongebob"}, {$set: {fullTime: true}} )db.students.updateOne( {_id: ObjectId("374687326asd)}, {$set: {fullTime: false}} )
- Syntax:
- Update many data
db.students.updateMany( {}, {$set: {fullTime: true}} ) - Remove field
db.students.updateOne( {name: "Spongebob"}, {$unset: {fullTime: ""}} ) - Check if field exist
db.students.updateMany( {fullTime: {$exists: false}}, {$set: {fullTime: true}} ) - Delete one data from collection
db.collectionName.deleteOne({name: "Larry"}) - Delete multiple data from collection
db.collectionName.deleteMany({fullTime: false})
Data type
db.collectionName.insertOne({
name: "Larry", // string
age: 24, // integer
gpa: 3.9 // float
isWorking: false, // boolean
registerDate: new Date(), // date
wife: null, // null object
courses: ["Biology", "Math", "Physics"], // array
address: {
city: "Queens",
province: "New York",
zip: 12789
} // nested document
})