Method bawaan mongosh yang satu ini menghemat ketikan, yang lain memformat keluaran, dan yang lain lagi menyembunyikan detail teknis di balik satu kata. Menyebutnya helper karena semuanya pembantu: help() untuk menunjukkan kemampuan objek, pretty() untuk tampilan rapi, toArray() dan forEach() untuk mengolah cursor, sampai it untuk melanjutkan hasil yang terpotong. Chapter ini memperkenalkan helper-helper tersebut beserta perilaku aslinya di mongosh 2.x.
Daftar Method lewat help() #
Objek database punya db.help() yang sudah kita lihat di Chapter Instalasi mongosh. Objek collection punya versinya sendiri — dan koleksi apa pun bisa dimintai daftar method, termasuk yang baru dibuat. Siapkan dulu database latihan berisi empat produk:
use latihan_shellOutput yang Dihasilkan:
switched to db latihan_shelldb.produk.insertMany([
{ nama: "Pensil", harga: 3000 },
{ nama: "Buku", harga: 12000 },
{ nama: "Penghapus", harga: 2500 },
{ nama: "Spidol", harga: 8000 }
])Output yang Dihasilkan:
{
acknowledged: true,
insertedIds: {
'0': ObjectId('6ad37f9a95a4fb5ca803d7e4'),
'1': ObjectId('6ad37f9a95a4fb5ca803d7e5'),
'2': ObjectId('6ad37f9a95a4fb5ca803d7e6'),
'3': ObjectId('6ad37f9a95a4fb5ca803d7e7')
}
}Sekarang minta daftar method milik koleksi produk:
db.produk.help()Output yang Dihasilkan (dipotong):
Collection Class:
aggregate Calculates aggregate values for the data in a collection or a view.
bulkWrite Performs multiple write operations with controls for order of execution.
count Returns the count of documents that would match a find() query for the collection or view.
countDocuments Returns the count of documents that match the query for a collection or view.
deleteMany Removes all documents that match the filter from a collection.
deleteOne Removes a single document from a collection.
distinct Finds the distinct values for a specified field across a single collection or view and returns the results in an array.
estimatedDocumentCount Returns the count of all documents in a collection or view.
find Selects documents in a collection or view.
findAndModify Modifies and returns a single document.
findOne Selects documents in a collection or view.Daftar lengkapnya panjang — dari operasi CRUD (insertOne, find, updateMany) sampai manajemen index (createIndex, getIndexes). Bila lupa nama method, help() adalah tempat bertanya pertama sebelum membuka dokumentasi. Ada pula helper diagnostik seperti db.printCollectionStats() yang mencetak statistik penyimpanan setiap collection di database aktif:
db.printCollectionStats()Output yang Dihasilkan (dipotong):
produk
{
ok: 1,
capped: false,
wiredTiger: {
metadata: { formatVersion: 1 },
creationString: 'access_pattern_hint=none,allocation_size=4KB,app_metadata=(formatVersion=1),assert=(commit_timestamp=none,durable_timestamp=none,read_timestamp=none,write_timestamp=off),block_allocation=best,block_compressor=snappy,block_manager=default,cache_resident=false,checksum=on,colgroups=,collator=,columns=,dictionary=0,disaggregated=(page_log=,storage_tier=none),encryption=(keyid=,name=),exclusive=false,extractor=,format=btree,huffman_key=,huffman_value=,ignore_in_memory_cache_size=false,immutable=false,import=(compare_timestamps=oldest_timestamp,enabled=false),metadata_file=,panic_corrupt=true,repair=false),in_memory=false,ingest=,internal_item_max=0,internal_key_max=0,internal_key_truncate=true,internal_page_max=4KB,key_format=q,key_gap=10,leaf_item_max=0,leaf_key_max=0,leaf_page_max=32KB,leaf_value_max=64MB,log=(enabled=false),lsm=(auto_throttle=,bloom=,bloom_bit_count=,bloom_config=,bloom_hash_count=,bloom_oldest=,chunk_count_limit=,chunk_max=,chunk_size=,merge_custom=(prefix=,start_generation=,suffix=),merge_max=,merge_min=,memory_page_image_max=0,memory_page_max=10M,os_cache_dirty_max=0,os_cache_max=0,prefix_compression=false,prefix_compression_min=4,source=,split_deepen_min_child=0,split_deepen_per_child=0,split_pct=90,stable=,tiered_storage=(auth_token=,bucket=,bucket_prefix=,cache_directory=,local_retention=300,name=,object_target_size=0),type=file,value_format=u,verbose=[],write_timestamp_usage=none)',
type: 'file',
uri: 'statistics:table:collection-d29da387-be1a-4be9-85b6-fbb8a82bc0ba',
version: 'WiredTiger 12.0.0: (November 15, 2024)',
autocommit: {Keluarannya memang panjang dan teknis — baris pertama menyebut nama collection (produk), diikuti statistik lengkap dari storage engine WiredTiger. Untuk pekerjaan harian, cukup ketahui keberadaannya; kita pakai penuh saat membahas performa di Section berikutnya.
pretty() Sudah Default di mongosh #
Pada shell lawas mongo, hasil find() dicetak sebagai satu baris JSON padat, dan .pretty() wajib ditambahkan agar bisa dibaca manusia. Di mongosh perilaku ini berubah: keluaran sudah otomatis rapi, field per baris dan berindentasi. Bandingkan dua perintah berikut:
db.produk.find().sort({ harga: -1 }).limit(2)Output yang Dihasilkan:
[
{
_id: ObjectId('6ad37f9f22cc103dc4812e8b'),
nama: 'Buku',
harga: 12000
},
{
_id: ObjectId('6ad37f9f22cc103dc4812e8d'),
nama: 'Spidol',
harga: 8000
}
]db.produk.find().sort({ harga: -1 }).limit(2).pretty()Output yang Dihasilkan:
[
{
_id: ObjectId('6ad37f9f22cc103dc4812e8b'),
nama: 'Buku',
harga: 12000
},
{
_id: ObjectId('6ad37f9f22cc103dc4812e8d'),
nama: 'Spidol',
harga: 8000
}
]Identik — .pretty() tetap dikenali demi kompatibilitas kebiasaan lama, tetapi tidak lagi diperlukan. Perhatikan juga rantai .sort({ harga: -1 }).limit(2) di contoh: -1 berarti urutan menurun, dan limit(2) memotong hasil menjadi dua document teratas. Kedua helper ini kita pakai penuh pada Section CRUD.
toArray() dan forEach() #
Cursor bisa diubah menjadi array JavaScript biasa lewat .toArray() — setelah itu seluruh method array tersedia, misalnya .map() untuk mengambil satu field:
db.produk.find().sort({ harga: -1 }).toArray().map(produk => produk.nama)Output yang Dihasilkan:
[ 'Buku', 'Spidol', 'Pensil', 'Penghapus' ]Untuk memproses hasil tanpa memuat semuanya sekaligus, forEach() menjalankan satu fungsi per document — pola yang sudah kita pakai di Chapter Menggunakan Variabel:
db.produk.find().forEach(produk => print(produk.nama + " Rp" + produk.harga))Output yang Dihasilkan:
Pensil Rp3000
Buku Rp12000
Penghapus Rp2500
Spidol Rp8000Pilih sesuai kebutuhan: toArray() saat hasil hendak dipakai berulang sebagai array, forEach() saat cukup sekali lewat.
Iterasi Cursor dengan it #
find() pada hasil besar menampilkan maksimal 20 document per layar, lalu berhenti dengan pesan Type "it" for more. Ketik it untuk melanjutkan ke bagian berikutnya. Siapkan collection berisi 22 peserta:
db.peserta.insertMany([
{ no: 1 }, { no: 2 }, { no: 3 }, { no: 4 },
{ no: 5 }, { no: 6 }, { no: 7 }, { no: 8 },
{ no: 9 }, { no: 10 }, { no: 11 }, { no: 12 },
{ no: 13 }, { no: 14 }, { no: 15 }, { no: 16 },
{ no: 17 }, { no: 18 }, { no: 19 }, { no: 20 },
{ no: 21 }, { no: 22 }
])Output yang Dihasilkan (dipotong):
{
acknowledged: true,
insertedIds: {
'0': ObjectId('6ad37fa022cc103dc4812e8e'),
'1': ObjectId('6ad37fa022cc103dc4812e8f'),
'2': ObjectId('6ad37fa022cc103dc4812e90'),
'3': ObjectId('6ad37fa022cc103dc4812e91'),
'4': ObjectId('6ad37fa022cc103dc4812e92'),
'5': ObjectId('6ad37fa022cc103dc4812e93'),
'6': ObjectId('6ad37fa022cc103dc4812e94'),
'7': ObjectId('6ad37fa022cc103dc4812e95'),
'8': ObjectId('6ad37fa022cc103dc4812e96'),
'9': ObjectId('6ad37fa022cc103dc4812e97'),
'10': ObjectId('6ad37fa022cc103dc4812e98'),
'11': ObjectId('6ad37fa022cc103dc4812e99'),
'12': ObjectId('6ad37fa022cc103dc4812e9a'),
'13': ObjectId('6ad37fa022cc103dc4812e9b'),
'14': ObjectId('6ad37fa022cc103dc4812e9c'),
'15': ObjectId('6ad37fa022cc103dc4812e9d'),
'16': ObjectId('6ad37fa022cc103dc4812e9e'),
'17': ObjectId('6ad37fa022cc103dc4812e9f'),
'18': ObjectId('6ad37fa022cc103dc4812ea0'),
'19': ObjectId('6ad37fa022cc103dc4812ea1'),
'20': ObjectId('6ad37fa022cc103dc4812ea2'),
'21': ObjectId('6ad37fa022cc103dc4812ea3')
}
}db.peserta.find()Output yang Dihasilkan:
[
{ _id: ObjectId('6ad37fa022cc103dc4812e8e'), no: 1 },
{ _id: ObjectId('6ad37fa022cc103dc4812e8f'), no: 2 },
{ _id: ObjectId('6ad37fa022cc103dc4812e90'), no: 3 },
{ _id: ObjectId('6ad37fa022cc103dc4812e91'), no: 4 },
{ _id: ObjectId('6ad37fa022cc103dc4812e92'), no: 5 },
{ _id: ObjectId('6ad37fa022cc103dc4812e93'), no: 6 },
{ _id: ObjectId('6ad37fa022cc103dc4812e94'), no: 7 },
{ _id: ObjectId('6ad37fa022cc103dc4812e95'), no: 8 },
{ _id: ObjectId('6ad37fa022cc103dc4812e96'), no: 9 },
{ _id: ObjectId('6ad37fa022cc103dc4812e97'), no: 10 },
{ _id: ObjectId('6ad37fa022cc103dc4812e98'), no: 11 },
{ _id: ObjectId('6ad37fa022cc103dc4812e99'), no: 12 },
{ _id: ObjectId('6ad37fa022cc103dc4812e9a'), no: 13 },
{ _id: ObjectId('6ad37fa022cc103dc4812e9b'), no: 14 },
{ _id: ObjectId('6ad37fa022cc103dc4812e9c'), no: 15 },
{ _id: ObjectId('6ad37fa022cc103dc4812e9d'), no: 16 },
{ _id: ObjectId('6ad37fa022cc103dc4812e9e'), no: 17 },
{ _id: ObjectId('6ad37fa022cc103dc4812e9f'), no: 18 },
{ _id: ObjectId('6ad37fa022cc103dc4812ea0'), no: 19 },
{ _id: ObjectId('6ad37fa022cc103dc4812ea1'), no: 20 }
]
Type "it" for moreDua puluh document tampil, dua sisanya menunggu. Lanjutkan dengan satu kata:
itOutput yang Dihasilkan:
[
{ _id: ObjectId('6ad37fa022cc103dc4812ea2'), no: 21 },
{ _id: ObjectId('6ad37fa022cc103dc4812ea3'), no: 22 }
]Sebelum menutup chapter, bersihkan database latihan:
db.dropDatabase()Output yang Dihasilkan:
{ ok: 1, dropped: 'latihan_shell' }Rangkuman #
db.<collection>.help()mendaftar method koleksi;db.printCollectionStats()mencetak statistik penyimpanan yang panjang dan teknis.mongoshsudah mencetak hasil secara rapi —.pretty()dikenali tetapi tidak lagi diperlukan..toArray()mengubah cursor menjadi array JavaScript (method array ikut tersedia);forEach()memproses document satu per satu..sort()mengurutkan (-1menurun) dan.limit()memotong jumlah hasil.itmelanjutkan cursor yang berhenti di 20 document; gantinya di skrip:hasNext()/next()atautoArray().