MongoDB adalah cross-platform, database berorientasi dokumen yang menyediakan, kinerja tinggi, ketersediaan tinggi, dan skalabilitas mudah. MongoDB bekerja pada konsep pengumpulan dan dokumen
Basis data
Database adalah wadah fisik untuk koleksi. Setiap database mendapatkan kumpulan file sendiri di sistem file. Satu server MongoDB biasanya memiliki banyak basis data
Koleksi
Koleksi adalah sekelompok dokumen MongoDB. Ini setara dengan tabel RDBMS. Koleksi ada dalam satu database. Koleksi tidak menerapkan skema. Dokumen dalam koleksi dapat memiliki bidang yang berbeda. Biasanya, semua dokumen dalam kumpulan memiliki tujuan yang serupa atau terkait
Dokumen
Dokumen adalah kumpulan pasangan kunci-nilai. Dokumen memiliki skema dinamis. Skema dinamis berarti bahwa dokumen dalam koleksi yang sama tidak perlu memiliki rangkaian bidang atau struktur yang sama, dan bidang umum dalam dokumen kumpulan dapat menyimpan jenis data yang berbeda.
Tabel berikut menunjukkan hubungan terminologi RDBMS dengan MongoDB
RDBMSMongoDBDatabaseDatabaseTableCollectionTuple/RowDocumentcolumnFieldTable JoinEmbedded DocumentsPrimary KeyPrimary Key [Default key _id disediakan oleh mongodb sendiri]Database Server dan ClientMysqld/Oraclemongodmysql/sqlplusmongoContoh Dokumen
Contoh berikut menunjukkan struktur dokumen situs blog, yang hanya berupa pasangan nilai kunci yang dipisahkan koma
{ _id: ObjectId[7df78ad8902c] title: 'MongoDB Overview', description: 'MongoDB is no sql database', by: 'tutorials point', url: '//www.tutorialspoint.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100, comments: [ { user:'user1', message: 'My first comment', dateCreated: new Date[2011,1,20,2,15], like: 0 }, { user:'user2', message: 'My second comments', dateCreated: new Date[2011,1,25,7,45], like: 5 } ] }
_id adalah nomor heksadesimal 12 byte yang menjamin keunikan setiap dokumen. Anda dapat memberikan _id saat memasukkan dokumen. Jika Anda tidak menyediakan maka MongoDB menyediakan id unik untuk setiap dokumen. 12 byte ini 4 byte pertama untuk stempel waktu saat ini, 3 byte berikutnya untuk id mesin, 2 byte berikutnya untuk id proses server MongoDB dan 3 byte sisanya adalah VALUE inkremental sederhana
Setiap basis data relasional memiliki desain skema tipikal yang menunjukkan jumlah tabel dan hubungan antara tabel-tabel ini. Sedangkan di MongoDB, tidak ada konsep relasi
Keuntungan MongoDB dibandingkan RDBMS
Skema kurang - MongoDB adalah database dokumen di mana satu koleksi menyimpan dokumen yang berbeda. Jumlah bidang, konten, dan ukuran dokumen dapat berbeda dari satu dokumen ke dokumen lainnya
Struktur objek tunggal jelas
Tidak ada kompleks yang bergabung
Kemampuan permintaan yang mendalam. MongoDB mendukung kueri dinamis pada dokumen menggunakan bahasa kueri berbasis dokumen yang hampir sekuat SQL
Penyetelan
Kemudahan scale-out − MongoDB mudah untuk diskalakan
Konversi/pemetaan objek aplikasi ke objek database tidak diperlukan
Menggunakan memori internal untuk menyimpan perangkat kerja [windowed], memungkinkan akses data yang lebih cepat
Mengapa Menggunakan MongoDB?
Penyimpanan Berorientasi Dokumen - Data disimpan dalam bentuk dokumen gaya JSON
Indeks pada atribut apa pun
Replikasi dan ketersediaan tinggi
Pecahan otomatis
Kueri yang kaya
Pembaruan cepat di tempat
Dukungan profesional oleh MongoDB
Di mana Menggunakan MongoDB?
- Data besar
- Manajemen Konten dan Pengiriman
- Infrastruktur Seluler dan Sosial
- Manajemen Data Pengguna
- Pusat Data
Mari kita lihat cara menginstal MongoDB di Windows
Instal MongoDB Di Windows
Untuk menginstal MongoDB di Windows, unduh rilis terbaru MongoDB dari https. // www. mongodb. org/download. Pastikan Anda mendapatkan versi MongoDB yang benar tergantung pada versi Windows Anda. Untuk mendapatkan versi Windows Anda, buka command prompt dan jalankan perintah berikut
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_
MongoDB versi 32-bit hanya mendukung database yang lebih kecil dari 2GB dan hanya cocok untuk tujuan pengujian dan evaluasi
Sekarang ekstrak file unduhan Anda ke c. \ drive atau lokasi lainnya. Pastikan nama folder hasil ekstrak adalah mongodb-win32-i386-[version] atau mongodb-win32-x86_64-[version]. Di sini [versi] adalah versi unduhan MongoDB
Selanjutnya, buka command prompt dan jalankan perintah berikut
C:\>move mongodb-win64-* mongodb 1 dir[s] moved. C:\>
Jika Anda telah mengekstraksi MongoDB di lokasi yang berbeda, buka jalur itu dengan menggunakan perintah cd FOLDER/DIR dan sekarang jalankan proses yang diberikan di atas
MongoDB membutuhkan folder data untuk menyimpan file-nya. Lokasi default untuk direktori data MongoDB adalah c. \data\db. Jadi, Anda perlu membuat folder ini menggunakan Command Prompt. Jalankan urutan perintah berikut
C:\>md data C:\md data\db
Jika Anda harus menginstal MongoDB di lokasi yang berbeda, maka Anda perlu menentukan jalur alternatif untuk \data\db dengan menyetel jalur dbpath di mongod. exe. Untuk hal yang sama, keluarkan perintah berikut
Di prompt perintah, navigasikan ke direktori bin yang ada di folder instalasi MongoDB. Misalkan folder instalasi saya adalah D. \setup\mongodb
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_
Ini akan menampilkan menunggu koneksi pesan pada output konsol, yang menunjukkan bahwa mongod. proses exe berjalan dengan sukses
Sekarang untuk menjalankan MongoDB, Anda perlu membuka prompt perintah lain dan mengeluarkan perintah berikut
D:\set up\mongodb\bin>mongo.exe MongoDB shell version: 2.4.6 connecting to: test >db.test.save[ { a: 1 } ] >db.test.find[] { "_id" : ObjectId[5879b0f65a56a454], "a" : 1 } >
Ini akan menunjukkan bahwa MongoDB diinstal dan dijalankan dengan sukses. Lain kali ketika Anda menjalankan MongoDB, Anda hanya perlu mengeluarkan perintah
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" D:\set up\mongodb\bin>mongo.exe_
Instal MongoDB di Ubuntu
Jalankan perintah berikut untuk mengimpor kunci GPG publik MongoDB −
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
Buat file /etc/apt/sources. daftar. d/mongodb. daftar file menggunakan perintah berikut
echo 'deb //downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list_
Sekarang keluarkan perintah berikut untuk memperbarui repositori −
sudo apt-get update_
Selanjutnya instal MongoDB dengan menggunakan perintah berikut –
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_0
Pada instalasi di atas, 2. 2. 3 saat ini dirilis versi MongoDB. Pastikan untuk selalu menginstal versi terbaru. Sekarang MongoDB berhasil diinstal
Mulai MongoDB
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_1
Hentikan MongoDB
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_2
Mulai ulang MongoDB
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_3
Untuk menggunakan MongoDB jalankan perintah berikut
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_4
Ini akan menghubungkan Anda untuk menjalankan instance MongoDB
Bantuan MongoDB
Untuk mendapatkan daftar perintah, ketik db. help[] di klien MongoDB. Ini akan memberi Anda daftar perintah seperti yang ditunjukkan pada tangkapan layar berikut
Statistik MongoDB
Untuk mendapatkan statistik tentang server MongoDB, ketikkan perintah db. stats[] di klien MongoDB. Ini akan menunjukkan nama database, jumlah koleksi dan dokumen dalam database. Output dari perintah ditunjukkan pada screenshot berikut
Data di MongoDB memiliki skema yang fleksibel. dokumen dalam koleksi yang sama. Mereka tidak perlu memiliki kumpulan bidang atau struktur yang sama, dan bidang umum dalam dokumen kumpulan dapat menyimpan jenis data yang berbeda
Beberapa pertimbangan saat merancang Skema di MongoDB
Rancang skema Anda sesuai dengan kebutuhan pengguna
Gabungkan objek menjadi satu dokumen jika Anda akan menggunakannya bersama. Kalau tidak, pisahkan mereka [tetapi pastikan tidak perlu bergabung]
Gandakan data [tetapi terbatas] karena ruang disk lebih murah dibandingkan dengan waktu komputasi
Bergabunglah saat menulis, bukan saat membaca
Optimalkan skema Anda untuk kasus penggunaan yang paling sering
Lakukan agregasi kompleks dalam skema
Contoh
Misalkan klien membutuhkan desain database untuk blog/situs webnya dan melihat perbedaan antara desain skema RDBMS dan MongoDB. Situs web memiliki persyaratan berikut
- Setiap posting memiliki judul, deskripsi, dan url yang unik
- Setiap posting dapat memiliki satu atau lebih tag
- Setiap posting memiliki nama penerbitnya dan jumlah suka
- Setiap posting memiliki komentar yang diberikan oleh pengguna bersama dengan nama, pesan, data-waktu dan suka
- Di setiap posting, mungkin ada nol atau lebih komentar
Dalam skema RDBMS, desain untuk persyaratan di atas akan memiliki minimal tiga tabel
Sedangkan dalam skema MongoDB, desain akan memiliki satu pos koleksi dan struktur berikut −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_5
Jadi saat menampilkan data, di RDBMS Anda perlu menggabungkan tiga tabel dan di MongoDB, data hanya akan ditampilkan dari satu kumpulan
Dalam bab ini, kita akan melihat cara membuat database di MongoDB
Perintah Penggunaan
MongoDB use DATABASE_NAME digunakan untuk membuat database. Perintah akan membuat database baru jika tidak ada, jika tidak maka akan mengembalikan database yang ada
Sintaksis
Sintaks dasar penggunaan pernyataan DATABASE adalah sebagai berikut −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_6
Contoh
Jika Anda ingin menggunakan database dengan nama , maka gunakan pernyataan DATABASE sebagai berikut −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_7
Untuk memeriksa database yang Anda pilih saat ini, gunakan perintah db
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_8
Jika Anda ingin memeriksa daftar database Anda, gunakan perintah show dbs
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_9
Basis data yang Anda buat [mydb] tidak ada dalam daftar. Untuk menampilkan database, Anda perlu memasukkan setidaknya satu dokumen ke dalamnya
C:\>move mongodb-win64-* mongodb 1 dir[s] moved. C:\>0
Dalam database default MongoDB adalah tes. Jika Anda tidak membuat database apa pun, koleksi akan disimpan di database pengujian
Pada bab ini, kita akan melihat cara menjatuhkan database menggunakan perintah MongoDB
Metode dropDatabase[]
MongoDB db. perintah dropDatabase[] digunakan untuk menjatuhkan database yang sudah ada
Sintaksis
Sintaks dasar perintah dropDatabase[] adalah sebagai berikut −
C:\>move mongodb-win64-* mongodb 1 dir[s] moved. C:\>1
Ini akan menghapus database yang dipilih. Jika Anda belum memilih basis data apa pun, maka itu akan menghapus basis data 'tes' default
Contoh
Pertama, periksa daftar database yang tersedia dengan menggunakan perintah show dbs
C:\>move mongodb-win64-* mongodb 1 dir[s] moved. C:\>2
Jika Anda ingin menghapus database baru, maka perintah dropDatabase[] adalah sebagai berikut –
C:\>move mongodb-win64-* mongodb 1 dir[s] moved. C:\>_3
Sekarang periksa daftar database
C:\>move mongodb-win64-* mongodb 1 dir[s] moved. C:\>_4
Dalam bab ini, kita akan melihat cara membuat koleksi menggunakan MongoDB
Metode createCollection[]
MongoDB db. createCollection[name, options] digunakan untuk membuat koleksi
Sintaksis
Sintaks dasar perintah createCollection[] adalah sebagai berikut −
C:\>move mongodb-win64-* mongodb 1 dir[s] moved. C:\>5
Pada perintah, nama adalah nama koleksi yang akan dibuat. Opsi adalah dokumen dan digunakan untuk menentukan konfigurasi koleksi
ParameterTypeDescriptionNameStringName koleksi yang akan dibuatOptionsDocument[Opsional] Tentukan opsi tentang ukuran memori dan pengindeksanParameter opsi bersifat opsional, jadi Anda hanya perlu menentukan nama koleksi. Berikut ini adalah daftar opsi yang dapat Anda gunakan −
FieldTypeDescriptioncappedBoolean[Opsional] Jika benar, aktifkan koleksi yang dibatasi. Koleksi yang dibatasi adalah koleksi ukuran tetap yang secara otomatis menimpa entri terlama saat mencapai ukuran maksimumnya. Jika Anda menentukan true, Anda juga perlu menentukan parameter ukuran. autoIndexIdBoolean[Opsional] Jika benar, buat indeks secara otomatis pada bidang _id. s Nilai default salah. sizenumber[Opsional] Menentukan ukuran maksimum dalam byte untuk koleksi yang dibatasi. Jika capped benar, maka Anda perlu menentukan bidang ini juga. maxnumber[Opsional] Menentukan jumlah maksimum dokumen yang diperbolehkan dalam koleksi yang dibatasiSaat memasukkan dokumen, MongoDB pertama-tama memeriksa bidang ukuran koleksi yang dibatasi, lalu memeriksa bidang maks
Contoh
Sintaks dasar metode createCollection[] tanpa opsi adalah sebagai berikut −
C:\>move mongodb-win64-* mongodb 1 dir[s] moved. C:\>6
Anda dapat memeriksa koleksi yang dibuat dengan menggunakan perintah tampilkan koleksi
C:\>move mongodb-win64-* mongodb 1 dir[s] moved. C:\>7
Contoh berikut menunjukkan sintaks metode createCollection[] dengan beberapa opsi penting −
C:\>move mongodb-win64-* mongodb 1 dir[s] moved. C:\>_8
Di MongoDB, Anda tidak perlu membuat koleksi. MongoDB membuat koleksi secara otomatis, saat Anda memasukkan beberapa dokumen
C:\>move mongodb-win64-* mongodb 1 dir[s] moved. C:\>_9
Dalam bab ini, kita akan melihat cara menjatuhkan koleksi menggunakan MongoDB
Metode drop[]
DB MongoDB. koleksi. drop[] digunakan untuk menjatuhkan koleksi dari database
Sintaksis
Sintaks dasar perintah drop[] adalah sebagai berikut −
C:\>md data C:\md data\db0
Contoh
Pertama, periksa koleksi yang tersedia ke dalam database mydb Anda
C:\>md data C:\md data\db1
Sekarang jatuhkan koleksi dengan nama mycollection
C:\>md data C:\md data\db2
Sekali lagi periksa daftar koleksi ke dalam database
C:\>md data C:\md data\db_3
metode drop[] akan mengembalikan true, jika koleksi yang dipilih berhasil dijatuhkan, jika tidak maka akan mengembalikan false
MongoDB mendukung banyak tipe data. Beberapa dari mereka adalah -
String − Ini adalah tipe data yang paling umum digunakan untuk menyimpan data. String di MongoDB harus valid UTF-8
Integer - Jenis ini digunakan untuk menyimpan nilai numerik. Bilangan bulat bisa 32 bit atau 64 bit tergantung pada server Anda
Boolean − Tipe ini digunakan untuk menyimpan nilai boolean [true/false].
Double – Tipe ini digunakan untuk menyimpan nilai floating point
Tombol Min/ Max − Jenis ini digunakan untuk membandingkan nilai dengan elemen BSON terendah dan tertinggi
Array − Jenis ini digunakan untuk menyimpan array atau daftar atau beberapa nilai ke dalam satu kunci
Stempel waktu − cap waktu. Ini berguna untuk merekam saat dokumen telah dimodifikasi atau ditambahkan
Objek − Tipe data ini digunakan untuk dokumen yang disematkan
Null – Tipe ini digunakan untuk menyimpan nilai Null
Simbol − tipe data ini digunakan identik dengan string;
Date − Tipe data ini digunakan untuk menyimpan tanggal atau waktu saat ini dalam format waktu UNIX. Anda dapat menentukan waktu tanggal Anda sendiri dengan membuat objek Tanggal dan memasukkan hari, bulan, tahun ke dalamnya
Object ID − Tipe data ini digunakan untuk menyimpan ID dokumen
Data biner − Tipe data ini digunakan untuk menyimpan data biner
Kode − Tipe data ini digunakan untuk menyimpan kode JavaScript ke dalam dokumen
Ekspresi reguler − Tipe data ini digunakan untuk menyimpan ekspresi reguler
Pada bab ini, kita akan mempelajari cara menyisipkan dokumen ke dalam koleksi MongoDB
Metode insert[]
Untuk memasukkan data ke dalam koleksi MongoDB, Anda perlu menggunakan metode insert[] atau save[] dari MongoDB
Sintaksis
Sintaks dasar dari perintah insert[] adalah sebagai berikut −
C:\>md data C:\md data\db_4
Contoh
C:\>md data C:\md data\db5
Di sini mycol adalah nama koleksi kami, seperti yang dibuat di bab sebelumnya. Jika koleksi tidak ada di database, maka MongoDB akan membuat koleksi ini dan memasukkan dokumen ke dalamnya
Dalam dokumen yang disisipkan, jika kita tidak menentukan parameter _id, maka MongoDB menetapkan ObjectId unik untuk dokumen ini
_id adalah nomor heksadesimal 12 byte unik untuk setiap dokumen dalam koleksi. 12 byte dibagi sebagai berikut −
C:\>md data C:\md data\db6
Untuk menyisipkan banyak dokumen dalam satu kueri, Anda dapat mengirimkan larik dokumen dalam perintah insert[]
Contoh
C:\>md data C:\md data\db_7
Untuk menyisipkan dokumen Anda dapat menggunakan db. pos. simpan [dokumen] juga. Jika Anda tidak menentukan _id dalam dokumen maka metode save[] akan bekerja sama dengan metode insert[]. Jika Anda menentukan _id maka itu akan menggantikan seluruh data dokumen yang berisi _id seperti yang ditentukan dalam metode save[]
Pada bab ini, kita akan belajar bagaimana melakukan query dokumen dari koleksi MongoDB
Metode find[]
Untuk meminta data dari koleksi MongoDB, Anda perlu menggunakan metode find[] MongoDB
Sintaksis
Sintaks dasar metode find[] adalah sebagai berikut −
C:\>md data C:\md data\db8
metode find[] akan menampilkan semua dokumen dengan cara yang tidak terstruktur
Metode cantik[]
Untuk menampilkan hasil dengan cara yang diformat, Anda dapat menggunakan metode pretty[]
Sintaksis
C:\>md data C:\md data\db_9
Contoh
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_0
Selain metode find[], ada metode findOne[], yang hanya mengembalikan satu dokumen
RDBMS Dimana Klausul Setara di MongoDB
Untuk menanyakan dokumen berdasarkan beberapa kondisi, Anda dapat menggunakan operasi berikut
OperationSyntaxExampleRDBMS EquivalentEquality{:}db.mycol.find[{"by":"tutorials point"}].pretty[]where by = 'tutorials point'Less Than{:{$lt:}}db.mycol.find[{"likes":{$lt:50}}].pretty[]where likes < 50Less Than Equals{:{$lte:}}db.mycol.find[{"likes":{$lte:50}}].pretty[]where likes 50Greater Than Equals{:{$gte:}}db.mycol.find[{"likes":{$gte:50}}].pretty[]where likes >= 50Not Equals{:{$ne:}}db.mycol.find[{"likes":{$ne:50}}].pretty[]where likes != 50DAN di MongoDB
Sintaksis
Dalam metode find[], jika Anda melewatkan beberapa kunci dengan memisahkannya dengan ',' maka MongoDB akan memperlakukannya sebagai kondisi AND. Berikut ini adalah sintaks dasar AND −
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_1
Contoh
Contoh berikut akan menampilkan semua tutorial yang ditulis oleh 'tutorials point' dan berjudul 'MongoDB Overview'
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_2
Untuk contoh yang diberikan di atas, klausa yang setara akan menjadi ' where by = 'tutorials point' AND title = 'MongoDB Overview' '. Anda dapat melewatkan sejumlah kunci, pasangan nilai dalam klausa find
ATAU di MongoDB
Sintaksis
Untuk menanyakan dokumen berdasarkan kondisi ATAU, Anda perlu menggunakan kata kunci $or. Berikut ini adalah sintaks dasar OR −
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_3
Contoh
Contoh berikut akan menampilkan semua tutorial yang ditulis oleh 'tutorials point' atau yang berjudul 'MongoDB Overview'
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_4
Menggunakan DAN dan ATAU Bersama-sama
Contoh
Contoh berikut akan menunjukkan dokumen yang memiliki suka lebih dari 10 dan yang judulnya adalah 'Ikhtisar MongoDB' atau dengan 'poin tutorial'. SQL yang setara di mana klausa adalah 'di mana suka> 10 DAN [oleh = 'poin tutorial' ATAU judul = 'Ikhtisar MongoDB']'
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_5
Metode update[] dan save[] MongoDB digunakan untuk memperbarui dokumen menjadi koleksi. Metode update[] memperbarui nilai dalam dokumen yang ada sementara metode save[] menggantikan dokumen yang ada dengan dokumen yang diteruskan dalam metode save[]
Pembaruan MongoDB [] Metode
Metode update[] memperbarui nilai dalam dokumen yang ada
Sintaksis
Sintaks dasar metode update[] adalah sebagai berikut −
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_6
Contoh
Pertimbangkan koleksi mycol memiliki data berikut
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_7
Contoh berikut akan menetapkan judul baru 'Tutorial MongoDB Baru' dari dokumen yang berjudul 'Ikhtisar MongoDB'
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_8
Secara default, MongoDB hanya akan memperbarui satu dokumen. Untuk memperbarui banyak dokumen, Anda perlu menyetel parameter 'multi' ke true
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_9
Metode Simpan MongoDB [].
Metode save[] menggantikan dokumen yang ada dengan dokumen baru yang diteruskan dalam metode save[]
Sintaksis
Sintaks dasar metode MongoDB save[] ditunjukkan di bawah ini −
D:\set up\mongodb\bin>mongo.exe MongoDB shell version: 2.4.6 connecting to: test >db.test.save[ { a: 1 } ] >db.test.find[] { "_id" : ObjectId[5879b0f65a56a454], "a" : 1 } >0
Contoh
Contoh berikut akan mengganti dokumen dengan _id '5983548781331adf45ec5'
D:\set up\mongodb\bin>mongo.exe MongoDB shell version: 2.4.6 connecting to: test >db.test.save[ { a: 1 } ] >db.test.find[] { "_id" : ObjectId[5879b0f65a56a454], "a" : 1 } >1
Pada bab ini, kita akan mempelajari cara menghapus dokumen menggunakan MongoDB
Metode hapus[]
Metode remove[] MongoDB digunakan untuk menghapus dokumen dari koleksi. metode remove[] menerima dua parameter. Salah satunya adalah kriteria penghapusan dan yang kedua adalah bendera justOne
kriteria penghapusan − [Opsional] kriteria penghapusan menurut dokumen akan dihapus
justOne − [Opsional] jika disetel ke true atau 1, maka hapus hanya satu dokumen
Sintaksis
Sintaks dasar metode remove[] adalah sebagai berikut −
D:\set up\mongodb\bin>mongo.exe MongoDB shell version: 2.4.6 connecting to: test >db.test.save[ { a: 1 } ] >db.test.find[] { "_id" : ObjectId[5879b0f65a56a454], "a" : 1 } >2
Contoh
Pertimbangkan koleksi mycol memiliki data berikut
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_7
Contoh berikut akan menghapus semua dokumen yang berjudul 'Tinjauan MongoDB'
D:\set up\mongodb\bin>mongo.exe MongoDB shell version: 2.4.6 connecting to: test >db.test.save[ { a: 1 } ] >db.test.find[] { "_id" : ObjectId[5879b0f65a56a454], "a" : 1 } >_4
Hapus Hanya Satu
Jika ada beberapa record dan Anda hanya ingin menghapus record pertama, setel parameter justOne dalam metode remove[]
D:\set up\mongodb\bin>mongo.exe MongoDB shell version: 2.4.6 connecting to: test >db.test.save[ { a: 1 } ] >db.test.find[] { "_id" : ObjectId[5879b0f65a56a454], "a" : 1 } >5
Hapus Semua Dokumen
Jika Anda tidak menentukan kriteria penghapusan, MongoDB akan menghapus seluruh dokumen dari koleksi. Ini setara dengan perintah truncate SQL
D:\set up\mongodb\bin>mongo.exe MongoDB shell version: 2.4.6 connecting to: test >db.test.save[ { a: 1 } ] >db.test.find[] { "_id" : ObjectId[5879b0f65a56a454], "a" : 1 } >_6
Di MongoDB, proyeksi berarti hanya memilih data yang diperlukan daripada memilih seluruh data dokumen. Jika dokumen memiliki 5 bidang dan Anda hanya perlu menampilkan 3 bidang, maka pilih hanya 3 bidang dari bidang tersebut
Metode find[]
Metode find[] MongoDB, dijelaskan dalam Dokumen Kueri MongoDB menerima parameter opsional kedua yaitu daftar bidang yang ingin Anda ambil. Di MongoDB, ketika Anda menjalankan metode find[], maka itu akan menampilkan semua bidang dokumen. Untuk membatasi ini, Anda perlu mengatur daftar bidang dengan nilai 1 atau 0. 1 digunakan untuk menampilkan field sedangkan 0 digunakan untuk menyembunyikan field
Sintaksis
Sintaks dasar metode find[] dengan proyeksi adalah sebagai berikut −
D:\set up\mongodb\bin>mongo.exe MongoDB shell version: 2.4.6 connecting to: test >db.test.save[ { a: 1 } ] >db.test.find[] { "_id" : ObjectId[5879b0f65a56a454], "a" : 1 } >_7
Contoh
Pertimbangkan koleksi mycol memiliki data berikut −
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_7
Contoh berikut akan menampilkan judul dokumen saat menanyakan dokumen
D:\set up\mongodb\bin>mongo.exe MongoDB shell version: 2.4.6 connecting to: test >db.test.save[ { a: 1 } ] >db.test.find[] { "_id" : ObjectId[5879b0f65a56a454], "a" : 1 } >_9
Harap diperhatikan bidang _id selalu ditampilkan saat menjalankan metode find[], jika Anda tidak menginginkan bidang ini, maka Anda perlu menyetelnya sebagai 0
Pada bab ini, kita akan mempelajari cara membatasi record menggunakan MongoDB
Metode Limit[]
Untuk membatasi record di MongoDB, Anda perlu menggunakan metode limit[]. Metode ini menerima satu argumen tipe angka, yang merupakan jumlah dokumen yang ingin Anda tampilkan
Sintaksis
Sintaks dasar metode limit[] adalah sebagai berikut −
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" D:\set up\mongodb\bin>mongo.exe_0
Contoh
Pertimbangkan koleksi myycol memiliki data berikut
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_7
Contoh berikut hanya akan menampilkan dua dokumen saat menanyakan dokumen
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" D:\set up\mongodb\bin>mongo.exe_2
Jika Anda tidak menentukan argumen angka dalam metode limit[] maka itu akan menampilkan semua dokumen dari koleksi
Metode Lewati MongoDB [].
Selain metode limit[], ada satu lagi metode skip[] yang juga menerima argumen tipe angka dan digunakan untuk melewatkan jumlah dokumen
Sintaksis
Sintaks dasar dari metode skip[] adalah sebagai berikut −
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" D:\set up\mongodb\bin>mongo.exe_3
Contoh
Contoh berikut hanya akan menampilkan dokumen kedua
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" D:\set up\mongodb\bin>mongo.exe_4
Harap diperhatikan, nilai default dalam metode skip[] adalah 0
Dalam bab ini, kita akan mempelajari cara mengurutkan catatan di MongoDB
Metode sort[]
Untuk mengurutkan dokumen di MongoDB, Anda perlu menggunakan metode sort[]. Metode menerima dokumen yang berisi daftar bidang beserta urutan penyortirannya. Untuk menentukan urutan penyortiran 1 dan -1 digunakan. 1 digunakan untuk urutan menaik sedangkan -1 digunakan untuk urutan menurun
Sintaksis
Sintaks dasar metode sort[] adalah sebagai berikut −
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" D:\set up\mongodb\bin>mongo.exe_5
Contoh
Pertimbangkan koleksi myycol memiliki data berikut
C:\Users\XYZ>d: D:\>cd "set up" D:\set up>cd mongodb D:\set up\mongodb>cd bin D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"_7
Contoh berikut akan menampilkan dokumen yang diurutkan berdasarkan judul dalam urutan menurun
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" D:\set up\mongodb\bin>mongo.exe_7
Perhatikan, jika Anda tidak menentukan preferensi pengurutan, maka metode sort[] akan menampilkan dokumen dalam urutan menaik
Indeks mendukung resolusi kueri yang efisien. Tanpa indeks, MongoDB harus memindai setiap dokumen koleksi untuk memilih dokumen yang cocok dengan pernyataan kueri. Pemindaian ini sangat tidak efisien dan membutuhkan MongoDB untuk memproses data dalam jumlah besar
Indeks adalah struktur data khusus, yang menyimpan sebagian kecil kumpulan data dalam bentuk yang mudah dilintasi. Indeks menyimpan nilai bidang tertentu atau kumpulan bidang, diurutkan berdasarkan nilai bidang sebagaimana ditentukan dalam indeks
Metode createIndex[]
Untuk membuat indeks, Anda perlu menggunakan metode createIndex[] dari MongoDB
Sintaksis
Sintaks dasar metode createIndex[] adalah sebagai berikut[]
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" D:\set up\mongodb\bin>mongo.exe_8
Di sini kuncinya adalah nama bidang tempat Anda ingin membuat indeks dan 1 untuk urutan menaik. To create index in descending order you need to use -1
Contoh
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" D:\set up\mongodb\bin>mongo.exe9
In createIndex[] method you can pass multiple fields, to create index on multiple fields
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB100
This method also accepts list of options [which are optional]. Following is the list −
ParameterTypeDescriptionbackgroundBooleanBuilds the index in the background so that building an index does not block other database activities. Specify true to build in the background. The default value is false. uniqueBooleanCreates a unique index so that the collection will not accept insertion of documents where the index key or keys match an existing value in the index. Specify true to create a unique index. The default value is false. namestringThe name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order. sparseBooleanIf true, the index only references documents with the specified field. These indexes use less space but behave differently in some situations [particularly sorts]. The default value is false. expireAfterSecondsintegerSpecifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection. weightsdocumentThe weight is a number ranging from 1 to 99,999 and denotes the significance of the field relative to the other indexed fields in terms of the score. default_languagestringFor a text index, the language that determines the list of stop words and the rules for the stemmer and tokenizer. The default value is English. language_overridestringFor a text index, specify the name of the field in the document that contains, the language to override the default language. The default value is languageThe dropIndex[] method
You can drop a particular index using the dropIndex[] method of MongoDB
Sintaksis
The basic syntax of DropIndex[] method is as follows[]
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB101
Here, "key" is the name of the file on which you want to remove an existing index. Instead of the index specification document [above syntax], you can also specify the name of the index directly as
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB102
Contoh
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB103
The dropIndexes[] method
This method deletes multiple [specified] indexes on a collection
Sintaksis
The basic syntax of DropIndexes[] method is as follows[] −
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB104
Contoh
Assume we have created 2 indexes in the named mycol collection as shown below −
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB105
Following example removes the above created indexes of mycol −
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB106
The getIndexes[] method
This method returns the description of all the indexes int the collection
Sintaksis
Following is the basic syntax od the getIndexes[] method −
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB107
Contoh
Assume we have created 2 indexes in the named mycol collection as shown below −
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB105
Following example retrieves all the indexes in the collection mycol −
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB109
Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. In SQL count[*] and with group by is an equivalent of mongodb aggregation
The aggregate[] Method
For the aggregation in MongoDB, you should use aggregate[] method
Sintaksis
Basic syntax of aggregate[] method is as follows −
echo 'deb //downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list0
Contoh
In the collection you have the following data −
echo 'deb //downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list1
Now from the above collection, if you want to display a list stating how many tutorials are written by each user, then you will use the following aggregate[] method −
echo 'deb //downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list2
Sql equivalent query for the above use case will be select by_user, count[*] from mycol group by by_user
In the above example, we have grouped documents by field by_user and on each occurrence of by_user previous value of sum is incremented. Following is a list of available aggregation expressions
ExpressionDescriptionExample$sumSums up the defined value from all documents in the collection. db. mycol. aggregate[[{$group . {_id . "$by_user", num_tutorial . {$sum . "$likes"}}}]]$avgCalculates the average of all given values from all documents in the collection. db. mycol. agregat[[{$grup. {_id . "$by_user", num_tutorial . {$avg . "$likes"}}}]]$minGets the minimum of the corresponding values from all documents in the collection. db. mycol. aggregate[[{$group . {_id . "$by_user", num_tutorial . {$min . "$likes"}}}]]$maxGets the maximum of the corresponding values from all documents in the collection. db. mycol. aggregate[[{$group . {_id . "$by_user", num_tutorial . {$max . "$suka"}}}]]$pushMenyisipkan nilai ke larik dalam dokumen hasil. db. mycol. aggregate[[{$group . {_id . "$by_user", url . {$push. "$url"}}}]]$addToSetInserts the value to an array in the resulting document but does not create duplicates. db. mycol. agregat[[{$grup. {_pengenal. "$oleh_pengguna", url. {$addToSet. "$url"}}}]]$firstMendapatkan dokumen pertama dari dokumen sumber sesuai dengan pengelompokannya. Biasanya ini hanya masuk akal bersama dengan beberapa tahap "$sort" yang diterapkan sebelumnya. db. mycol. aggregate[[{$group . {_id . "$by_user", first_url . {$first . "$url"}}}]]$lastGets the last document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage. db. mycol. aggregate[[{$group . {_id . "$by_user", last_url . {$last . "$url"}}}]]Pipeline Concept
In UNIX command, shell pipeline means the possibility to execute an operation on some input and use the output as the input for the next command and so on. MongoDB also supports same concept in aggregation framework. There is a set of possible stages and each of those is taken as a set of documents as an input and produces a resulting set of documents [or the final resulting JSON document at the end of the pipeline]. This can then in turn be used for the next stage and so on
Following are the possible stages in aggregation framework −
$project − Used to select some specific fields from a collection
$match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage
$group − This does the actual aggregation as discussed above
$sort − Sorts the documents
$skip − With this, it is possible to skip forward in the list of documents for a given amount of documents
$limit − This limits the amount of documents to look at, by the given number starting from the current positions
$unwind − This is used to unwind document that are using arrays. When using an array, the data is kind of pre-joined and this operation will be undone with this to have individual documents again. Thus with this stage we will increase the amount of documents for the next stage
Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers. Replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup
Why Replication?
- To keep your data safe
- High [24*7] availability of data
- Pemulihan bencana
- No downtime for maintenance [like backups, index rebuilds, compaction]
- Read scaling [extra copies to read from]
- Replica set is transparent to the application
How Replication Works in MongoDB
MongoDB achieves replication by the use of replica set. A replica set is a group of mongod instances that host the same data set. In a replica, one node is primary node that receives all write operations. All other instances, such as secondaries, apply operations from the primary so that they have the same data set. Replica set can have only one primary node
Replica set is a group of two or more nodes [generally minimum 3 nodes are required]
In a replica set, one node is primary node and remaining nodes are secondary
All data replicates from primary to secondary node
At the time of automatic failover or maintenance, election establishes for primary and a new primary node is elected
After the recovery of failed node, it again join the replica set and works as a secondary node
A typical diagram of MongoDB replication is shown in which client application always interact with the primary node and the primary node then replicates the data to the secondary nodes
Replica Set Features
- A cluster of N nodes
- Any one node can be primary
- All write operations go to primary
- Automatic failover
- Automatic recovery
- Consensus election of primary
Set Up a Replica Set
In this tutorial, we will convert standalone MongoDB instance to a replica set. To convert to replica set, following are the steps −
Shutdown already running MongoDB server
Start the MongoDB server by specifying -- replSet option. Following is the basic syntax of --replSet −
echo 'deb //downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list3
Contoh
echo 'deb //downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list4
It will start a mongod instance with the name rs0, on port 27017
Now start the command prompt and connect to this mongod instance
In Mongo client, issue the command rs. initiate[] to initiate a new replica set
To check the replica set configuration, issue the command rs. conf[]. To check the status of replica set issue the command rs. status[]
Add Members to Replica Set
To add members to replica set, start mongod instances on multiple machines. Now start a mongo client and issue a command rs. add[]
Sintaksis
The basic syntax of rs. add[] command is as follows −
echo 'deb //downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list5
Contoh
Suppose your mongod instance name is mongod1. net and it is running on port 27017. To add this instance to replica set, issue the command rs. add[] in Mongo client
echo 'deb //downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list6
You can add mongod instance to replica set only when you are connected to primary node. To check whether you are connected to primary or not, issue the command db. isMaster[] in mongo client
Sharding is the process of storing data records across multiple machines and it is MongoDB's approach to meeting the demands of data growth. As the size of the data increases, a single machine may not be sufficient to store the data nor provide an acceptable read and write throughput. Sharding solves the problem with horizontal scaling. With sharding, you add more machines to support data growth and the demands of read and write operations
Why Sharding?
- In replication, all writes go to master node
- Latency sensitive queries still go to master
- Single replica set has limitation of 12 nodes
- Memory can't be large enough when active dataset is big
- Local disk is not big enough
- Vertical scaling is too expensive
Sharding in MongoDB
The following diagram shows the sharding in MongoDB using sharded cluster
In the following diagram, there are three main components −
Shards − Shards are used to store data. They provide high availability and data consistency. In production environment, each shard is a separate replica set
Config Servers − Config servers store the cluster's metadata. This data contains a mapping of the cluster's data set to the shards. The query router uses this metadata to target operations to specific shards. In production environment, sharded clusters have exactly 3 config servers
Router Kueri - Router kueri pada dasarnya adalah instance mongo, berinteraksi dengan aplikasi klien dan mengarahkan operasi ke beling yang sesuai. The query router processes and targets the operations to shards and then returns results to the clients. A sharded cluster can contain more than one query router to divide the client request load. A client sends requests to one query router. Generally, a sharded cluster have many query routers
In this chapter, we will see how to create a backup in MongoDB
Dump MongoDB Data
To create backup of database in MongoDB, you should use mongodump command. This command will dump the entire data of your server into the dump directory. There are many options available by which you can limit the amount of data or create backup of your remote server
Sintaksis
The basic syntax of mongodump command is as follows −
echo 'deb //downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list7
Contoh
Start your mongod server. Assuming that your mongod server is running on the localhost and port 27017, open a command prompt and go to the bin directory of your mongodb instance and type the command mongodump
Pertimbangkan koleksi mycol memiliki data berikut
echo 'deb //downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list7
The command will connect to the server running at 127. 0. 0. 1 and port 27017 and back all data of the server to directory /bin/dump/. Following is the output of the command −
Following is a list of available options that can be used with the mongodump command
SyntaxDescriptionExamplemongodump --host HOST_NAME --port PORT_NUMBERThis commmand will backup all databases of specified mongod instance. mongodump --host tutorialspoint. com --port 27017mongodump --dbpath DB_PATH --out BACKUP_DIRECTORYThis command will backup only specified database at specified path. mongodump --dbpath /data/db/ --out /data/backup/mongodump --collection COLLECTION --db DB_NAMEThis command will backup only specified collection of specified database. mongodump --collection mycol --db testRestore data
To restore backup data MongoDB's mongorestore command is used. This command restores all of the data from the backup directory
Sintaksis
The basic syntax of mongorestore command is −
echo 'deb //downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list9
Following is the output of the command −
When you are preparing a MongoDB deployment, you should try to understand how your application is going to hold up in production. It’s a good idea to develop a consistent, repeatable approach to managing your deployment environment so that you can minimize any surprises once you’re in production
The best approach incorporates prototyping your set up, conducting load testing, monitoring key metrics, and using that information to scale your set up. The key part of the approach is to proactively monitor your entire system - this will help you understand how your production system will hold up before deploying, and determine where you will need to add capacity. Having insight into potential spikes in your memory usage, for example, could help put out a write-lock fire before it starts
To monitor your deployment, MongoDB provides some of the following commands −
mongostat
This command checks the status of all running mongod instances and return counters of database operations. These counters include inserts, queries, updates, deletes, and cursors. Perintah juga menunjukkan saat Anda menekan kesalahan halaman, dan menampilkan persentase kunci Anda. Ini berarti Anda kehabisan memori, menekan kapasitas tulis, atau mengalami masalah kinerja
To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongostat
sudo apt-get update0
Following is the output of the command −
mongotop
This command tracks and reports the read and write activity of MongoDB instance on a collection basis. By default, mongotop returns information in each second, which you can change it accordingly. You should check that this read and write activity matches your application intention, and you’re not firing too many writes to the database at a time, reading too frequently from a disk, or are exceeding your working set size
To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongotop
sudo apt-get update1
Following is the output of the command −
To change mongotop command to return information less frequently, specify a specific number after the mongotop command
sudo apt-get update2
Contoh di atas akan mengembalikan nilai setiap 30 detik
Terlepas dari alat MongoDB, 10gen menyediakan layanan pemantauan gratis yang dihosting, Layanan Manajemen MongoDB [MMS], yang menyediakan dasbor dan memberi Anda gambaran tentang metrik dari seluruh klaster Anda
In this chapter, we will learn how to set up MongoDB JDBC driver
Installation
Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB JDBC driver and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up MongoDB JDBC driver
You need to download the jar from the path Download mongo. jar. Make sure to download the latest release of it
You need to include the mongo. jar into your classpath
Connect to Database
To connect database, you need to specify the database name, if the database doesn't exist then MongoDB creates it automatically
Following is the code snippet to connect to the database −
sudo apt-get update3
Now, let's compile and run the above program to create our database myDb as shown below
sudo apt-get update4
On executing, the above program gives you the following output
sudo apt-get update5
Create a Collection
To create a collection, createCollection[] method of com. mongodb. client. MongoDatabase class is used
Following is the code snippet to create a collection −
sudo apt-get update_6
On compiling, the above program gives you the following result −
sudo apt-get update7
Getting/Selecting a Collection
To get/select a collection from the database, getCollection[] method of com. mongodb. client. MongoDatabase class is used
Following is the program to get/select a collection −
sudo apt-get update8
On compiling, the above program gives you the following result −
sudo apt-get update9
Insert a Document
To insert a document into MongoDB, insert[] method of com. mongodb. client. MongoCollection class is used
Following is the code snippet to insert a document −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>00
On compiling, the above program gives you the following result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>01
Retrieve All Documents
To select all documents from the collection, find[] method of com. mongodb. client. MongoCollection class is used. This method returns a cursor, so you need to iterate this cursor
Following is the program to select all documents −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>02
On compiling, the above program gives you the following result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>03
Update Document
To update a document from the collection, updateOne[] method of com. mongodb. client. MongoCollection class is used
Following is the program to select the first document −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>04
On compiling, the above program gives you the following result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>05
Delete a Document
To delete a document from the collection, you need to use the deleteOne[] method of the com. mongodb. client. MongoCollection class
Following is the program to delete a document −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>06
On compiling, the above program gives you the following result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>07
Dropping a Collection
To drop a collection from a database, you need to use the drop[] method of the com. mongodb. client. MongoCollection class
Following is the program to delete a collection −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>08
On compiling, the above program gives you the following result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>09
Listing All the Collections
To list all the collections in a database, you need to use the listCollectionNames[] method of the com. mongodb. client. MongoDatabase class
Following is the program to list all the collections of a database −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>10
On compiling, the above program gives you the following result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>11
Remaining MongoDB methods save[], limit[], skip[], sort[] etc. work same as explained in the subsequent tutorial
To use MongoDB with PHP, you need to use MongoDB PHP driver. Download the driver from the url Download PHP Driver. Make sure to download the latest release of it. Now unzip the archive and put php_mongo. dll in your PHP extension directory ["ext" by default] and add the following line to your php. ini file −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>12
Make a Connection and Select a Database
To make a connection, you need to specify the database name, if the database doesn't exist then MongoDB creates it automatically
Following is the code snippet to connect to the database −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>13
When the program is executed, it will produce the following result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>14
Create a Collection
Following is the code snippet to create a collection −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_15
When the program is executed, it will produce the following result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>16
Insert a Document
To insert a document into MongoDB, insert[] method is used
Following is the code snippet to insert a document −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>17
When the program is executed, it will produce the following result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>18
Find All Documents
To select all documents from the collection, find[] method is used
Following is the code snippet to select all documents −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>19
When the program is executed, it will produce the following result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>20
Update a Document
To update a document, you need to use the update[] method
In the following example, we will update the title of inserted document to MongoDB Tutorial. Following is the code snippet to update a document −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>21
When the program is executed, it will produce the following result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>22
Delete a Document
To delete a document, you need to use remove[] method
In the following example, we will remove the documents that has the title MongoDB Tutorial. Following is the code snippet to delete a document −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>23
When the program is executed, it will produce the following result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>24
In the above example, the second parameter is boolean type and used for justOne field of remove[] method
Remaining MongoDB methods findOne[], save[], limit[], skip[], sort[] etc. works same as explained above
Relationships in MongoDB represent how various documents are logically related to each other. Relationships can be modeled via Embedded and Referenced approaches. Such relationships can be either 1. 1, 1. N, N. 1 or N. N
Let us consider the case of storing addresses for users. Jadi, satu pengguna dapat memiliki banyak alamat yang menjadikan ini 1. N relationship
Following is the sample document structure of user document −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_25
Following is the sample document structure of address document −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>26
Modeling Embedded Relationships
In the embedded approach, we will embed the address document inside the user document
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_27
Pendekatan ini memelihara semua data terkait dalam satu dokumen, yang membuatnya mudah untuk diambil dan dipelihara. Seluruh dokumen dapat diambil dalam satu permintaan seperti -
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_28
Perhatikan bahwa dalam kueri di atas, db dan pengguna masing-masing adalah basis data dan koleksi
Kekurangannya adalah jika ukuran dokumen yang disematkan terus membesar, hal itu dapat memengaruhi kinerja baca/tulis
Modeling Referenced Relationships
This is the approach of designing normalized relationship. In this approach, both the user and address documents will be maintained separately but the user document will contain a field that will reference the address document's id field
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>29
As shown above, the user document contains the array field address_ids which contains ObjectIds of corresponding addresses. Using these ObjectIds, we can query the address documents and get address details from there. With this approach, we will need two queries. first to fetch the address_ids fields from user document and second to fetch these addresses from address collection
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>30
As seen in the last chapter of MongoDB relationships, to implement a normalized database structure in MongoDB, we use the concept of Referenced Relationships also referred to as Manual References in which we manually store the referenced document's id inside other document. However, in cases where a document contains references from different collections, we can use MongoDB DBRefs
DBRefs vs Manual References
As an example scenario, where we would use DBRefs instead of manual references, consider a database where we are storing different types of addresses [home, office, mailing, etc. ] in different collections [address_home, address_office, address_mailing, etc]. Now, when a user collection's document references an address, it also needs to specify which collection to look into based on the address type. In such scenarios where a document references documents from many collections, we should use DBRefs
Using DBRefs
There are three fields in DBRefs −
$ref − This field specifies the collection of the referenced document
$id − This field specifies the _id field of the referenced document
$db − This is an optional field and contains the name of the database in which the referenced document lies
Consider a sample user document having DBRef field address as shown in the code snippet −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>31
The address DBRef field here specifies that the referenced address document lies in address_home collection under tutorialspoint database and has an id of 534009e4d852427820000002
The following code dynamically looks in the collection specified by $ref parameter [address_home in our case] for a document with id as specified by $id parameter in DBRef
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>32
The above code returns the following address document present in address_home collection −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>33
In this chapter, we will learn about covered queries
What is a Covered Query?
As per the official MongoDB documentation, a covered query is a query in which −
- Semua bidang dalam kueri adalah bagian dari indeks
- All the fields returned in the query are in the same index
Since all the fields present in the query are part of an index, MongoDB matches the query conditions and returns the result using the same index without actually looking inside the documents. Since indexes are present in RAM, fetching data from indexes is much faster as compared to fetching data by scanning documents
Using Covered Queries
To test covered queries, consider the following document in the users collection −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>34
We will first create a compound index for the users collection on the fields gender and user_name using the following query −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>35
Now, this index will cover the following query −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>36
That is to say that for the above query, MongoDB would not go looking into database documents. Instead it would fetch the required data from indexed data which is very fast
Since our index does not include _id field, we have explicitly excluded it from result set of our query, as MongoDB by default returns _id field in every query. So the following query would not have been covered inside the index created above −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>37
Lastly, remember that an index cannot cover a query if −
- Any of the indexed fields is an array
- Any of the indexed fields is a subdocument
Analyzing queries is a very important aspect of measuring how effective the database and indexing design is. We will learn about the frequently used $explain and $hint queries
Using $explain
The $explain operator provides information on the query, indexes used in a query and other statistics. It is very useful when analyzing how well your indexes are optimized
In the last chapter, we had already created an index for the users collection on fields gender and user_name using the following query −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>35
We will now use $explain on the following query −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>39
The above explain[] query returns the following analyzed result −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>40
We will now look at the fields in this result set −
The true value of indexOnly indicates that this query has used indexing
The cursor field specifies the type of cursor used. BTreeCursor type indicates that an index was used and also gives the name of the index used. BasicCursor indicates that a full scan was made without using any indexes
n indicates the number of documents matching returned
nscannedObjects indicates the total number of documents scanned
nscanned indicates the total number of documents or index entries scanned
Using $hint
The $hint operator forces the query optimizer to use the specified index to run a query. This is particularly useful when you want to test performance of a query with different indexes. For example, the following query specifies the index on fields gender and user_name to be used for this query −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>41
To analyze the above query using $explain −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>42
Model Data for Atomic Operations
The recommended approach to maintain atomicity would be to keep all the related information, which is frequently updated together in a single document using embedded documents. This would make sure that all the updates for a single document are atomic
Consider the following products document −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>43
In this document, we have embedded the information of the customer who buys the product in the product_bought_by field. Now, whenever a new customer buys the product, we will first check if the product is still available using product_available field. If available, we will reduce the value of product_available field as well as insert the new customer's embedded document in the product_bought_by field. We will use findAndModify command for this functionality because it searches and updates the document in the same go
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>44
Our approach of embedded document and using findAndModify query makes sure that the product purchase information is updated only if it the product is available. And the whole of this transaction being in the same query, is atomic
In contrast to this, consider the scenario where we may have kept the product availability and the information on who has bought the product, separately. In this case, we will first check if the product is available using the first query. Then in the second query we will update the purchase information. However, it is possible that between the executions of these two queries, some other user has purchased the product and it is no more available. Without knowing this, our second query will update the purchase information based on the result of our first query. This will make the database inconsistent because we have sold a product which is not available
Consider the following document of the users collection −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>45
The above document contains an address sub-document and a tags array
Indexing Array Fields
Suppose we want to search user documents based on the user’s tags. For this, we will create an index on tags array in the collection
Creating an index on array in turn creates separate index entries for each of its fields. So in our case when we create an index on tags array, separate indexes will be created for its values music, cricket and blogs
To create an index on tags array, use the following code −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>46
After creating the index, we can search on the tags field of the collection like this −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>47
To verify that proper indexing is used, use the following explain command −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>48
The above command resulted in "cursor" . "BtreeCursor tags_1" yang mengonfirmasi bahwa pengindeksan yang tepat telah digunakan
Indexing Sub-Document Fields
Suppose that we want to search documents based on city, state and pincode fields. Since all these fields are part of address sub-document field, we will create an index on all the fields of the sub-document
For creating an index on all the three fields of the sub-document, use the following code −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>49
Once the index is created, we can search for any of the sub-document fields utilizing this index as follows −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>50
Remember that the query expression has to follow the order of the index specified. So the index created above would support the following queries −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>51
It will also support the following query −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>52
In this chapter, we will learn about Indexing Limitations and its other components
Extra Overhead
Every index occupies some space as well as causes an overhead on each insert, update and delete. So if you rarely use your collection for read operations, it makes sense not to use indexes
RAM Usage
Since indexes are stored in RAM, you should make sure that the total size of the index does not exceed the RAM limit. If the total size increases the RAM size, it will start deleting some indexes, causing performance loss
Query Limitations
Indexing can't be used in queries which use −
- Regular expressions or negation operators like $nin, $not, etc
- Arithmetic operators like $mod, etc
- $where clause
Hence, it is always advisable to check the index usage for your queries
Index Key Limits
Starting from version 2. 6, MongoDB will not create an index if the value of existing index field exceeds the index key limit
Inserting Documents Exceeding Index Key Limit
MongoDB will not insert any document into an indexed collection if the indexed field value of this document exceeds the index key limit. Same is the case with mongorestore and mongoimport utilities
Maximum Ranges
- Koleksi tidak boleh memiliki lebih dari 64 indeks
- The length of the index name cannot be longer than 125 characters
- A compound index can have maximum 31 fields indexed
We have been using MongoDB Object Id in all the previous chapters. In this chapter, we will understand the structure of ObjectId
An ObjectId is a 12-byte BSON type having the following structure −
- The first 4 bytes representing the seconds since the unix epoch
- The next 3 bytes are the machine identifier
- The next 2 bytes consists of process id
- The last 3 bytes are a random counter value
MongoDB menggunakan ObjectIds sebagai nilai default bidang _id dari setiap dokumen, yang dihasilkan saat pembuatan dokumen apa pun. Kombinasi kompleks ObjectId membuat semua bidang _id menjadi unik
Membuat ObjectId Baru
Untuk menghasilkan ObjectId baru gunakan kode berikut −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_53
Pernyataan di atas mengembalikan id − yang dihasilkan secara unik berikut ini
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_54
Alih-alih MongoDB menghasilkan ObjectId, Anda juga dapat memberikan id 12-byte
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_55
Membuat Timestamp dari Dokumen
Karena _id ObjectId secara default menyimpan stempel waktu 4-byte, dalam banyak kasus Anda tidak perlu menyimpan waktu pembuatan dokumen apa pun. Anda dapat mengambil waktu pembuatan dokumen menggunakan metode getTimestamp −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_56
Ini akan mengembalikan waktu pembuatan dokumen ini dalam format tanggal ISO −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_57
Mengubah ObjectId menjadi String
Dalam beberapa kasus, Anda mungkin memerlukan nilai ObjectId dalam format string. Untuk mengonversi ObjectId dalam string, gunakan kode berikut −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_58
Kode di atas akan mengembalikan format string dari Guid −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_59
Sesuai dokumentasi MongoDB, Pengurangan peta adalah paradigma pemrosesan data untuk memadatkan volume data yang besar menjadi hasil agregat yang berguna. MongoDB menggunakan perintah mapReduce untuk operasi pengurangan peta. MapReduce umumnya digunakan untuk memproses kumpulan data besar
Perintah MapReduce
Berikut ini adalah sintaks dari perintah dasar mapReduce −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_60
Fungsi map-reduce pertama-tama menanyakan koleksi, lalu memetakan dokumen hasil untuk memancarkan pasangan kunci-nilai, yang kemudian dikurangi berdasarkan kunci yang memiliki banyak nilai
Dalam sintaks di atas -
peta adalah fungsi javascript yang memetakan nilai dengan kunci dan memancarkan pasangan kunci-nilai
pengurangan adalah fungsi javascript yang mengurangi atau mengelompokkan semua dokumen yang memiliki kunci yang sama
out menentukan lokasi hasil kueri pengurangan peta
kueri menentukan kriteria pemilihan opsional untuk memilih dokumen
sort menentukan kriteria sortir opsional
limit menentukan jumlah maksimum opsional dokumen yang akan dikembalikan
Menggunakan MapReduce
Pertimbangkan struktur dokumen berikut yang menyimpan posting pengguna. Dokumen menyimpan nama_pengguna pengguna dan status kiriman
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_61
Sekarang, kita akan menggunakan fungsi mapReduce pada koleksi kiriman kita untuk memilih semua kiriman aktif, mengelompokkannya berdasarkan nama_pengguna dan kemudian menghitung jumlah kiriman oleh setiap pengguna menggunakan kode berikut –
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_62
Permintaan mapReduce di atas menampilkan hasil berikut -
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_63
Hasilnya menunjukkan bahwa total 4 dokumen cocok dengan kueri [status. "aktif"], fungsi peta mengeluarkan 4 dokumen dengan pasangan kunci-nilai dan akhirnya fungsi pengurangan mengelompokkan dokumen yang dipetakan memiliki kunci yang sama menjadi 2
Untuk melihat hasil dari query mapReduce ini, gunakan operator find −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_64
Kueri di atas memberikan hasil berikut yang menunjukkan bahwa tom dan mark pengguna memiliki dua pos dalam keadaan aktif −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_65
Dengan cara yang sama, kueri MapReduce dapat digunakan untuk membuat kueri agregasi kompleks yang besar. Penggunaan fungsi Javascript khusus memanfaatkan MapReduce yang sangat fleksibel dan kuat
Mulai dari versi 2. 4, MongoDB mulai mendukung indeks teks untuk mencari di dalam konten string. Pencarian Teks menggunakan teknik stemming untuk mencari kata-kata tertentu di bidang string dengan menghilangkan kata-kata stop stemming seperti a, an, the, dll. Saat ini, MongoDB mendukung sekitar 15 bahasa
Mengaktifkan Pencarian Teks
Awalnya, Text Search merupakan fitur eksperimental namun dimulai dari versi 2. 6, konfigurasi diaktifkan secara default. Tetapi jika Anda menggunakan MongoDB versi sebelumnya, Anda harus mengaktifkan pencarian teks dengan kode berikut –
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_66
Membuat Indeks Teks
Pertimbangkan dokumen berikut di bawah koleksi posting yang berisi teks posting dan tagnya −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_67
Kami akan membuat indeks teks pada bidang post_text sehingga kami dapat mencari di dalam teks posting kami -
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_68
Menggunakan Indeks Teks
Sekarang kita telah membuat indeks teks pada bidang post_text, kita akan mencari semua posting yang memiliki kata tutorialspoint dalam teksnya
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_69
Perintah di atas mengembalikan dokumen hasil berikut yang memiliki kata tutorialspoint dalam teks postingannya −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_70
Jika Anda menggunakan MongoDB versi lama, Anda harus menggunakan perintah berikut −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_71
Menggunakan Pencarian Teks sangat meningkatkan efisiensi pencarian dibandingkan dengan pencarian normal
Menghapus Indeks Teks
Untuk menghapus indeks teks yang ada, pertama-tama temukan nama indeks menggunakan kueri berikut −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_72
Setelah mendapatkan nama indeks Anda dari kueri di atas, jalankan perintah berikut. Di sini, post_text_text adalah nama indeks
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_73
Ekspresi Reguler sering digunakan dalam semua bahasa untuk mencari pola atau kata dalam string apa pun. MongoDB juga menyediakan fungsionalitas ekspresi reguler untuk pencocokan pola string menggunakan operator $regex. MongoDB menggunakan PCRE [Perl Compatible Regular Expression] sebagai bahasa ekspresi reguler
Tidak seperti pencarian teks, kita tidak perlu melakukan konfigurasi atau perintah apa pun untuk menggunakan ekspresi reguler
Pertimbangkan struktur dokumen berikut di bawah kumpulan posting yang berisi teks posting dan tagnya −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_67
Menggunakan ekspresi regex
Permintaan regex berikut mencari semua posting yang berisi string tutorialspoint di dalamnya −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_75
Permintaan yang sama juga dapat ditulis sebagai -
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_76
Menggunakan Ekspresi regex dengan Case Insensitive
Untuk membuat case pencarian tidak sensitif, kami menggunakan parameter $options dengan nilai $i. Perintah berikut akan mencari string yang memiliki kata tutorialspoint, terlepas dari huruf kecil atau huruf kapital −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_77
Salah satu hasil yang dikembalikan dari kueri ini adalah dokumen berikut yang berisi kata tutorialspoint dalam berbagai kasus −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_78
Menggunakan regex untuk Elemen Array
Kita juga bisa menggunakan konsep regex pada field array. Ini khususnya sangat penting saat kami menerapkan fungsi tag. Jadi, jika Anda ingin mencari semua posting yang memiliki tag yang dimulai dari kata tutorial [baik tutorial atau tutorial atau tutorialspoint atau tutorial php], Anda dapat menggunakan kode berikut −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_79
Mengoptimalkan Kueri Ekspresi Reguler
Jika bidang dokumen diindeks, kueri akan menggunakan manfaatkan nilai yang diindeks agar cocok dengan ekspresi reguler. Ini membuat pencarian menjadi sangat cepat dibandingkan dengan ekspresi reguler yang memindai seluruh koleksi
Jika ekspresi reguler adalah ekspresi awalan, semua kecocokan dimaksudkan untuk dimulai dengan karakter string tertentu. Untuk e. g. , jika ekspresi regex adalah ^tut, maka kueri harus mencari hanya string yang dimulai dengan tut
RockMongo adalah alat administrasi MongoDB yang dapat digunakan untuk mengelola server, basis data, koleksi, dokumen, indeks, dan banyak lagi lainnya. Ini memberikan cara yang sangat ramah pengguna untuk membaca, menulis, dan membuat dokumen. Ini mirip dengan alat PHPMyAdmin untuk PHP dan MySQL
Mengunduh RockMongo
Anda dapat mengunduh RockMongo versi terbaru dari sini. https. //github. com/iwind/rockmongo
Menginstal RockMongo
Setelah diunduh, Anda dapat meng-unzip paket di folder root server Anda dan mengganti nama folder yang diekstraksi menjadi rockmongo. Buka browser web apa saja dan akses index. halaman php dari folder rockmongo. Masukkan admin/admin sebagai nama pengguna/kata sandi masing-masing
Bekerja dengan RockMongo
Kami sekarang akan melihat beberapa operasi dasar yang dapat Anda lakukan dengan RockMongo
Membuat Basis Data Baru
Untuk membuat database baru, klik tab Databases. Klik Buat Database Baru. Di layar berikutnya, berikan nama database baru dan klik Buat. Anda akan melihat database baru ditambahkan di panel kiri
Membuat Koleksi Baru
Untuk membuat koleksi baru di dalam database, klik database tersebut dari panel kiri. Klik tautan Koleksi Baru di atas. Berikan nama koleksi yang diperlukan. Jangan khawatir tentang kolom Is Capped, Size, dan Max lainnya. Klik Buat. Koleksi baru akan dibuat dan Anda dapat melihatnya di panel kiri
Membuat Dokumen Baru
Untuk membuat dokumen baru, klik koleksi tempat Anda ingin menambahkan dokumen. Saat Anda mengklik sebuah koleksi, Anda akan dapat melihat semua dokumen di dalam koleksi tersebut yang terdaftar di sana. Untuk membuat dokumen baru, klik tautan Sisipkan di bagian atas. Anda dapat memasukkan data dokumen baik dalam format JSON atau array dan klik Simpan
Ekspor/Impor Data
Untuk mengimpor/mengekspor data koleksi apa pun, klik koleksi tersebut, lalu klik tautan Ekspor/Impor di panel atas. Ikuti petunjuk selanjutnya untuk mengekspor data Anda dalam format zip, lalu impor file zip yang sama untuk mengimpor kembali data
GridFS adalah spesifikasi MongoDB untuk menyimpan dan mengambil file besar seperti gambar, file audio, file video, dll. Ini semacam sistem file untuk menyimpan file tetapi datanya disimpan dalam koleksi MongoDB. GridFS memiliki kemampuan untuk menyimpan file bahkan lebih besar dari batas ukuran dokumennya yaitu 16MB
GridFS membagi file menjadi potongan-potongan dan menyimpan setiap potongan data dalam dokumen terpisah, masing-masing dengan ukuran maksimum 255k
GridFS secara default menggunakan dua koleksi fs. file dan fs. chunks untuk menyimpan metadata file dan chunks. Setiap potongan diidentifikasi oleh bidang _id ObjectId uniknya. fs. file berfungsi sebagai dokumen induk. Bidang files_id di fs. dokumen chunks menghubungkan chunk ke induknya
Berikut adalah contoh dokumen fs. koleksi file −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_80
Dokumen menentukan nama file, ukuran potongan, tanggal upload, dan panjang
Berikut adalah contoh dokumen fs. potongan dokumen −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_81
Menambahkan File ke GridFS
Sekarang, kami akan menyimpan file mp3 menggunakan GridFS menggunakan perintah put. Untuk ini, kami akan menggunakan mongofiles. utilitas exe hadir di folder bin dari folder instalasi MongoDB
Buka command prompt Anda, arahkan ke mongofiles. exe di folder bin dari folder instalasi MongoDB dan ketikkan kode berikut −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_82
Di sini, gridfs adalah nama database tempat file akan disimpan. Jika database tidak ada, MongoDB akan secara otomatis membuat dokumen baru dengan cepat. Lagu. mp3 adalah nama file yang diunggah. Untuk melihat dokumen file dalam database, Anda dapat menggunakan find query −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_83
Perintah di atas mengembalikan dokumen berikut −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_84
Kita juga bisa melihat semua potongan yang ada di fs. koleksi potongan yang terkait dengan file yang disimpan dengan kode berikut, menggunakan id dokumen yang dikembalikan dalam kueri sebelumnya −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_85
Dalam kasus saya, kueri mengembalikan 40 dokumen yang berarti seluruh dokumen mp3 dibagi menjadi 40 potongan data
Koleksi tertutup adalah koleksi melingkar ukuran tetap yang mengikuti urutan penyisipan untuk mendukung kinerja tinggi untuk membuat, membaca, dan menghapus operasi. Secara melingkar, itu berarti bahwa ketika ukuran tetap yang dialokasikan untuk koleksi habis, itu akan mulai menghapus dokumen terlama dalam koleksi tanpa memberikan perintah eksplisit apa pun.
Koleksi yang dibatasi membatasi pembaruan pada dokumen jika pembaruan menghasilkan peningkatan ukuran dokumen. Karena koleksi yang dibatasi menyimpan dokumen dalam urutan penyimpanan disk, ini memastikan bahwa ukuran dokumen tidak menambah ukuran yang dialokasikan pada disk. Koleksi yang dibatasi adalah yang terbaik untuk menyimpan informasi log, data cache, atau data volume tinggi lainnya
Membuat Koleksi Tertutup
Untuk membuat koleksi yang dibatasi, kami menggunakan perintah createCollection normal tetapi dengan opsi yang dibatasi sebagai true dan menentukan ukuran maksimum koleksi dalam byte
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_86
Selain ukuran koleksi, kita juga bisa membatasi jumlah dokumen dalam koleksi dengan menggunakan parameter max −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_87
Jika Anda ingin memeriksa apakah suatu koleksi dibatasi atau tidak, gunakan perintah berikut isCapped −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_88
Jika ada koleksi yang Anda rencanakan untuk diubah menjadi capped, Anda dapat melakukannya dengan kode berikut −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_89
Kode ini akan mengonversi pos koleksi kami yang ada menjadi koleksi yang dibatasi
Meminta Koleksi yang Dibatasi
Secara default, kueri pencarian pada koleksi yang dibatasi akan menampilkan hasil dalam urutan penyisipan. Tetapi jika Anda ingin dokumen diambil dalam urutan terbalik, gunakan perintah sortir seperti yang ditunjukkan pada kode berikut −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_90
Ada beberapa poin penting lainnya mengenai koleksi terbatas yang perlu diketahui -
Kami tidak dapat menghapus dokumen dari koleksi yang dibatasi
Tidak ada indeks default yang ada dalam koleksi yang dibatasi, bahkan pada bidang _id
Saat memasukkan dokumen baru, MongoDB sebenarnya tidak harus mencari tempat untuk menampung dokumen baru di disk. Itu dapat secara membabi buta memasukkan dokumen baru di bagian belakang koleksi. Ini membuat operasi penyisipan dalam koleksi yang dibatasi menjadi sangat cepat
Demikian pula, saat membaca dokumen, MongoDB mengembalikan dokumen dalam urutan yang sama seperti yang ada di disk. Ini membuat operasi baca sangat cepat
MongoDB tidak memiliki fungsionalitas penambahan otomatis bawaan, seperti database SQL. Secara default, ini menggunakan ObjectId 12-byte untuk bidang _id sebagai kunci utama untuk mengidentifikasi dokumen secara unik. Namun, mungkin ada skenario di mana kita mungkin ingin bidang _id memiliki nilai yang bertambah secara otomatis selain ObjectId
Karena ini bukan fitur default di MongoDB, kami secara terprogram akan mencapai fungsionalitas ini dengan menggunakan koleksi penghitung seperti yang disarankan oleh dokumentasi MongoDB
Menggunakan Koleksi Penghitung
Pertimbangkan dokumen produk berikut. Kami ingin bidang _id menjadi urutan bilangan bulat yang bertambah secara otomatis mulai dari 1,2,3,4 hingga n
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_91
Untuk ini, buat koleksi penghitung, yang akan melacak nilai urutan terakhir untuk semua bidang urutan
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_92
Sekarang, kita akan memasukkan dokumen berikut ke dalam koleksi counter dengan productid sebagai kuncinya −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_93
Bidang sequence_value melacak nilai terakhir dari urutan
Gunakan kode berikut untuk memasukkan dokumen urutan ini ke dalam koleksi penghitung −
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_94
Membuat Fungsi Javascript
Sekarang, kita akan membuat fungsi getNextSequenceValue yang akan mengambil nama urutan sebagai inputnya, menambah nomor urut dengan 1 dan mengembalikan nomor urut yang diperbarui. Dalam kasus kami, nama urutannya adalah productid
C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>_95
Menggunakan Fungsi Javascript
Kami sekarang akan menggunakan fungsi getNextSequenceValue saat membuat dokumen baru dan menetapkan nilai urutan yang dikembalikan sebagai bidang _id dokumen