Project Based Learning

 

Penerapan Database MongoDB dengan Visual Studio Code

Selamat datang kembali, para pembaca setia blog ini! Kali ini, kita akan memasuki dunia menarik pengaplikasian database NoSQL, khususnya MongoDB, dengan menggunakan alat yang sangat bermanfaat, yaitu Jupyter Notebook.

Apa itu MongoDB?

MongoDB merupakan salah satu jenis database NoSQL yang berbasis dokumen. Berbeda dengan database relasional tradisional, MongoDB menggunakan format BSON (Binary JSON) untuk menyimpan data. Keunggulan MongoDB terletak pada kemampuannya menangani data semi-struktural atau tidak terstruktur dengan lebih efisien.

Mengapa MongoDB?

Pertanyaan ini wajar muncul. MongoDB menjadi pilihan populer karena kemudahannya dalam menyimpan data yang beragam, skalabilitas horizontal yang baik, dan fleksibilitas dalam memodelkan data. Penerapan MongoDB seringkali memberikan solusi yang optimal untuk aplikasi yang membutuhkan penanganan data yang cepat dan terdistribusi.



Visualisasi & Filter Data, serta fungsi CRUD data.

Langkah - Langkah :

1. Import file datasheet yang akan dipakai ke MongoDB menggunakkan VS Code. pastikan file sudah csv dan nama sesuai dengan nama file. buat file pada VS Code dengan nama film.cvs

berikut kode untuk impor csv :

import csv
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client['UAS']
koleksi = db['UAS']

# Impor data dari file CSV ke MongoDB
path_csv = 'data.csv'

with open(path_csv, 'r') as csvfile:
    csv_reader = csv.DictReader(csvfile)
    for row in csv_reader:
        koleksi.insert_one(row)
    print("Data dari CSV berhasil diimpor ke MongoDB.")

2. Untuk menampilkan data dan fungsi CRUD, buat file app.py lalu isi dengan kode seperti dibawah ini :

# import csv
from flask import Flask, render_template, request, redirect
from pymongo import MongoClient
from bson import ObjectId

app = Flask(__name__)
client = MongoClient('mongodb://localhost:27017/')
db = client['UAS']
koleksi = db['UAS']

# Membaca file CSV dan memasukkan data ke MongoDB jika belum ada
# path_csv = 'ds_salaries.csv'

# with open(path_csv, 'r') as csvfile:
    # csv_reader = csv.DictReader(csvfile)
    # for row in csv_reader:
        # koleksi.insert_one(row)

# Rute untuk menampilkan data dari koleksi MongoDB
# @app.route('/')
def index():
    data_cursor = koleksi.find()
    formatted_data = []
    header = ['Time_submitted','Review','Rating','Total_thumbsup','Reply']

    for row in data_cursor:
        formatted_row = {key: row[key] for key in header}
        formatted_data.append(formatted_row)

    return render_template('index.html', data=formatted_data)

# Rute untuk menampilkan data dari koleksi MongoDB
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        query = request.form.get('query')
        if query:
            data_cursor = koleksi.find({
                '$or': [
                    {'Index': {'$regex': query, '$options': 'i'}},
                    {'id': {'$regex': query, '$options': 'i'}},
                    {'title': {'$regex': query, '$options': 'i'}},
                    {'type': {'$regex': query, '$options': 'i'}},
                    {'description': {'$regex': query, '$options': 'i'}},
                    {'release_year': {'$regex': query, '$options': 'i'}},

                ]
            })
            data_list = list(data_cursor)
            return render_template('index.html', data=data_list)
        else:
            return redirect('/')
    else:
        data_cursor = koleksi.find()
        data_list = list(data_cursor)
        return render_template('index.html', data=data_list)

# Rute untuk menambah data baru
@app.route('/add', methods=['POST'])
def add():
    new_data = {
        'Index': request.form['Index'],
        'id': request.form['id'],
        'title': request.form['title'],
        'type': request.form['type'],
        'description': request.form['description'],
        'release_year': request.form['release_year'],
    }
    koleksi.insert_one(new_data)
    return redirect('/')

# Rute untuk menghapus data
@app.route('/delete/<id>', methods=['GET'])
def delete(id):
    koleksi.delete_one({'_id': ObjectId(id)})
    return redirect('/')

# Rute untuk menampilkan form edit
@app.route('/edit/<id>', methods=['GET'])
def edit(id):
    data = koleksi.find_one({'_id': ObjectId(id)})
    return render_template('edit.html', data=data)

# Rute untuk menyimpan perubahan dari form edit
@app.route('/update/<id>', methods=['POST'])
def update(id):
    updated_data = {
        'Index': request.form['Index'],
        'id': request.form['id'],
        'title': request.form['title'],
        'type': request.form['type'],
        'description': request.form['description'],
        'release_year': request.form['release_year'],
    }
    koleksi.update_one({'_id': ObjectId(id)}, {'$set': updated_data})
    return redirect('/')

if __name__ == '__main__':
    app.run(debug=True)

3. Untuk menampilkan grafik, buat Buatlah file baru untuk menyimpan script html, terdapat 3 file yaitu index.html untuk mengatur tampilan halaman awal, edit.html untuk mengatur tampilan halaman edit, dan graph.html untuk mengatur tampilan halaman grafik.

Kode file index.html :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Data Netflix</title>
    <style>
      table {
        border-collapse: collapse;
        width: 100%;
      }

      th,
      td {
        border: 1px solid black;
        padding: 8px;
        text-align: left;
        max-width: 200px; /* Atur lebar maksimum untuk kolom */
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin: 4px; /* Menambahkan jarak pada setiap sisi */
      }

      th:nth-child(1),
      td:nth-child(1) {
        width: 8%; /* Atur lebar kolom work_year di sini */
      }

      th:nth-child(2),
      td:nth-child(2) {
        width: 8%; /* Atur lebar kolom experience_level di sini */
      }

      th:nth-child(3),
      td:nth-child(3) {
        width: 8%; /* Atur lebar kolom employment_type di sini */
      }

      th:nth-child(4),
      td:nth-child(4) {
        width: 16%; /* Atur lebar kolom job_title di sini */
      }

      th:nth-child(5),
      td:nth-child(5) {
        width: 8%; /* Atur lebar kolom salary di sini */
      }

      th:nth-child(6),
      td:nth-child(6) {
        width: 12%; /* Atur lebar kolom salary_currency di sini */
      }

      th:nth-child(7),
      td:nth-child(7) {
        width: 12%; /* Atur lebar kolom salary_in_usd di sini */
      }

      th:nth-child(8),
      td:nth-child(8) {
        width: 12%; /* Atur lebar kolom employee_residence di sini */
      }

      th:nth-child(9),
      td:nth-child(9) {
        width: 8%; /* Atur lebar kolom remote_ratio di sini */
      }

      th:nth-child(10),
      td:nth-child(10) {
        width: 12%; /* Atur lebar kolom company_location di sini */
      }

      th:nth-child(11),
      td:nth-child(11) {
        width: 8%; /* Atur lebar kolom company_size di sini */
      }

      /* Tambahkan margin-bottom untuk memberikan ruang antara form dan tabel */
      form {
        margin-bottom: 20px;
      }
    </style>
  </head>
  <body>
    <h1>Data Netflix</h1>
    <p>Data Length: {{ data|length }}</p>
    <form action="/" method="POST">
      <label for="search">Cari:</label>
      <input type="text" id="search" name="query" />
      <button type="submit">Cari</button>
    </form>
    <style>
      form {
        display: flex;
        flex-wrap: wrap;
      }

      div {
        flex: 0 0 10%; /* Setiap div akan menempati 30% dari lebar container */
        margin-right: 5%; /* Menambahkan jarak antara setiap div */
        margin-bottom: 15px; /* Menambahkan jarak antar baris */
      }
    </style>

    <form action="/add" method="POST">
      <div>
        <label for="Index">Index:</label>
        <input type="text" id="Index" name="Index" />
      </div>

      <div>
        <label for="id">id:</label>
        <input type="text" id="id" name="id" />
      </div>

      <div>
        <label for="title">title:</label>
        <input type="text" id="title" name="title" />
      </div>

      <div>
        <label for="type">type:</label>
        <input type="text" id="type" name="type" />
      </div>

      <div>
        <label for="description">description:</label>
        <input type="text" id="description" name="description" />
      </div>

      <div>
        <label for="release_year">release_year:</label>
        <input type="text" id="release_year" name="release_year" />
      </div>

      </div>
      <button
        type="submit"
        style="width: 150px; height: 25px; margin-top: 15px"
      >
        Tambah Data
      </button>
    </form>

    <table>
      <thead>
        <tr>
          <th>Index</th>
          <th>id</th>
          <th>title</th>
          <th>type</th>
          <th>description</th>
          <th>release_year</th>
        </tr>
      </thead>
      <tbody>
        {% for row in data %}
        <tr>
          <td>{{ row.Index }}</td>
          <td>{{ row.id }}</td>
          <td>{{ row.title }}</td>
          <td>{{ row.type }}</td>
          <td>{{ row.description }}</td>
          <td>{{ row.release_year }}</td>
          <td>
            <form action="/edit/{{ row._id }}" method="GET">
              <button type="submit">Edit Data</button>
            </form>
            <form action="/delete/{{ row._id }}" method="GET">
              <button type="submit">Hapus</button>
            </form>
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </body>
</html>


Kode file edit.html :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Edit Data</title>
    <style>
      /* Atur gaya sesuai kebutuhan Anda */
      form {
        display: flex;
        flex-direction: column;
        max-width: 300px; /* Sesuaikan lebar form jika diperlukan */
        margin: right; /* Pusatkan form di tengah halaman */
      }

      label {
        margin-bottom: 8px;
      }

      input {
        margin-bottom: 16px;
        padding: 8px;
      }

      button {
        padding: 8px;
      }
    </style>
  </head>
  <body>
    <h1>Edit Data</h1>
    <form action="/update/{{ data._id }}" method="POST">
      <label for="Index">Index:</label>
      <input
        type="text"
        id="Index"
        name="Index"
        value="{{ data.Index }}"
      />
      <!-- Isi formulir dengan data yang ada untuk diedit -->
      <label for="id">id:</label>
      <input
        type="text"
        id="id"
        name="id"
        value="{{ data.id }}"
      />
      <label for="title">title:</label>
      <input
        type="text"
        id="title"
        name="title"
        value="{{ data.title }}"
      />
      <label for="type">type:</label>
      <input
        type="text"
        id="type"
        name="type"
        value="{{ data.type }}"
      />
      <label for="description">description:</label>
      <input
        type="text"
        id="description"
        name="description"
        value="{{ data.description }}"
      />
      <label for="release_year">release_year:</label>
      <input
        type="text"
        id="release_year"
        name="release_year"
        value="{{ data.release_year }}"
      />
      <button type="submit">Update Data</button>
    </form>
  </body>
</html>


Hasil :

1. Tampilan awal



Pada halaman awal akan muncul data yang sudah diimport dan jumlah datanya. Di sini juga terdapat tools untuk melakukan pencarian berdasarkan kategori tertentu

hasilnya :





belum selesai pak


Komentar

Postingan populer dari blog ini

LOCAL/REMOTE FILE INCLUSION

DASAR WEB HACKING

BRUTE FORCE