jongle
v1.2.0
Published
Kompakt, hızlı ve güçlü bir JSON tabanlı veritabanı modülü
Maintainers
Readme
Jongle
Kompakt, hızlı ve güçlü bir JSON tabanlı veritabanı modülü. Yerel Node.js uygulamalarınız için MongoDB benzeri bir deneyim.
Özellikler
- JSON Tabanlı Depolama: Verileri dosya sistemi üzerinde JSON formatında saklar
- Zengin Sorgu API'si: MongoDB benzeri sorgu operatörleri (
$eq,$gt,$lt,$invb.) - Koleksiyon Yapısı: Verileri koleksiyonlar halinde düzenleme
- Şema Doğrulama: Veri doğrulama ve şema desteği
- Veri Şifreleme: Verilerinizi şifreleme desteği
- Yedekleme ve Geri Yükleme: Veritabanını yedekleme ve geri yükleme
- Indeksleme: Sorgu performansını artırmak için alanları indeksleme
- Aggregation Pipeline: Verileri toplu analiz etme için sorgular
- ACID Transactions: Veri bütünlüğü için temel transaction desteği
- Senkron ve Asenkron API: Promise tabanlı asenkron API
- TypeScript Desteği: Tam TypeScript desteği
Kurulum
npm install jongleKullanım Örnekleri
Temel Kullanım
import { Jongle } from 'jongle';
// Veritabanı oluştur
const db = new Jongle({
path: './my-database',
debug: true
});
// Bağlantıyı başlat
await db.connect();
// Bir koleksiyon al
const users = db.collection('users');
// Veri ekle
const userId = await users.insert({
name: 'Ahmet',
email: '[email protected]',
age: 30,
createdAt: new Date()
});
console.log(`Eklenen kullanıcı ID: ${userId}`);
// Veri sorgula
const allUsers = await users.find();
const youngUsers = await users.find({ age: { $lt: 25 } });
const ahmet = await users.findOne({ name: 'Ahmet' });
// Veri güncelle
await users.update(userId, {
age: 31,
lastLogin: new Date()
});
// Toplu güncelleme
const updatedCount = await users.updateMany(
{ age: { $gt: 30 } },
{ status: 'experienced' }
);
// Veri sil
await users.delete(userId);
// Filtreye uyan çoklu veri sil
await users.deleteMany({ status: 'inactive' });
// Bağlantıyı kapat
await db.close();Veri Silme İşlemleri
import { Jongle } from 'jongle';
const db = new Jongle();
await db.connect();
const users = db.collection('users');
// ID ile tek bir doküman silme
const userId = '550e8400-e29b-41d4-a716-446655440000';
const isDeleted = await users.delete(userId);
console.log(`Kullanıcı silindi mi: ${isDeleted}`);
// Belirli bir kritere göre çoklu silme
const deletedCount = await users.deleteMany({ active: false });
console.log(`${deletedCount} pasif kullanıcı silindi`);
// Belirli bir tarihten önce oluşturulmuş tüm kullanıcıları silme
const oldDate = new Date('2020-01-01');
const oldUsersDeleted = await users.deleteMany({
createdAt: { $lt: oldDate }
});
console.log(`${oldUsersDeleted} eski kullanıcı silindi`);
// Belirli rollere sahip kullanıcıları silme
const deletedByRole = await users.deleteMany({
roles: { $in: ['guest', 'temporary'] }
});
console.log(`${deletedByRole} geçici kullanıcı silindi`);
// Tüm koleksiyonu temizleme (tüm dokümanları silme)
await users.drop();
console.log('Tüm kullanıcılar silindi');
// Bir koleksiyonu tamamen kaldırma
await db.dropCollection('users');
console.log('Kullanıcılar koleksiyonu kaldırıldı');Veri Yönetimi ve Bakım
import { Jongle } from 'jongle';
const db = new Jongle({
path: './my-database',
debug: true
});
await db.connect();
// Veritabanındaki koleksiyonları listele
const collections = await db.listCollections();
console.log('Mevcut koleksiyonlar:', collections);
// Bir koleksiyonu yeniden adlandırma (manuel olarak)
if (await db.hasCollection('users')) {
const users = db.collection('users');
const userData = await users.find();
// Yeni koleksiyon oluştur
const members = db.collection('members');
// Verileri yeni koleksiyona aktar
await members.insertMany(userData);
// Eski koleksiyonu sil
await db.dropCollection('users');
console.log('Koleksiyon yeniden adlandırıldı: users -> members');
}
// Bir koleksiyonu yedekle
const logs = db.collection('logs');
const logData = await logs.find();
// Arşiv koleksiyonu oluştur
const archivedLogs = db.collection('logs_archive_2023');
await archivedLogs.insertMany(logData);
// Artık ihtiyaç duyulmayan eskimiş verileri temizle
await logs.deleteMany({
createdAt: { $lt: new Date('2023-01-01') }
});
console.log('Eski loglar arşivlendi ve silindi');
// Veritabanını temizleme (performans optimizasyonu için)
await db.close();
await db.connect();
console.log('Veritabanı bağlantısı yenilendi');Güvenli Veri Silme ve İşlemleri
import { Jongle } from 'jongle';
const db = new Jongle();
await db.connect();
const users = db.collection('users');
// İşlem içinde güvenli silme
try {
await db.transaction(async (session) => {
const users = session.collection('users');
const posts = session.collection('posts');
// Kullanıcıyı sil
const userId = '7f8d9e6c-5b4a-3f2e-1d0c-9a8b7c6d5e4f';
await users.delete(userId);
// Kullanıcıya ait tüm gönderileri de sil
await posts.deleteMany({ authorId: userId });
console.log('Kullanıcı ve tüm gönderileri başarıyla silindi');
});
} catch (error) {
console.error('Silme işlemi sırasında hata oluştu, hiçbir veri silinmedi', error);
}
// Koşullu silme (bulunmazsa hata vermeden)
const deleteIfExists = async (id) => {
const user = await users.findById(id);
if (user) {
await users.delete(id);
return true;
}
return false;
};
const wasDeleted = await deleteIfExists('non-existent-id');
console.log(`Silme işlemi gerçekleşti mi: ${wasDeleted}`);
// Yumuşak silme (soft delete) - tamamen silmek yerine işaretleme
await users.update('some-user-id', {
isDeleted: true,
deletedAt: new Date()
});
// Yumuşak silinen kullanıcıları sorgulama hariç tutma
const activeUsers = await users.find({
$or: [
{ isDeleted: false },
{ isDeleted: { $exists: false } }
]
});
console.log(`${activeUsers.length} aktif kullanıcı bulundu`);
// Belirli bir süre sonra yumuşak silinen kullanıcıları tamamen temizleme
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
const cleanupResult = await users.deleteMany({
isDeleted: true,
deletedAt: { $lt: thirtyDaysAgo }
});
console.log(`${cleanupResult} eski silinmiş kullanıcı tamamen kaldırıldı`);Şema Doğrulama
import { Jongle, SchemaDefinition } from 'jongle';
const db = new Jongle();
await db.connect();
// Bir şema tanımla
const userSchema: SchemaDefinition = {
strict: true, // Şemada bulunmayan alanlar reddedilecek
timestamps: true, // createdAt ve updatedAt alanları otomatik eklenecek
name: {
type: 'string',
required: true,
string: {
minLength: 2,
maxLength: 50
}
},
email: {
type: 'string',
required: true,
string: {
match: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
lowercase: true,
trim: true
}
},
age: {
type: 'number',
number: {
minimum: 18,
maximum: 120,
integer: true
}
},
active: {
type: 'boolean',
default: true
},
roles: {
type: 'array',
array: {
minItems: 1,
maxItems: 5,
items: {
type: 'string',
string: {
enum: ['user', 'admin', 'editor']
}
}
}
},
address: {
street: { type: 'string' },
city: { type: 'string' },
country: { type: 'string' }
},
birthday: {
type: 'date',
date: {
minDate: '1900-01-01',
maxDate: new Date()
}
},
settings: {
type: 'object',
object: {
properties: {
theme: {
type: 'string',
string: {
enum: ['light', 'dark', 'system']
},
default: 'system'
},
notifications: { type: 'boolean', default: true }
}
}
},
// Özel doğrulama fonksiyonu
password: {
type: 'string',
required: true,
string: {
minLength: 8
},
validate: (value) => {
// En az bir büyük harf, bir küçük harf ve bir rakam içermeli
if (!/[A-Z]/.test(value)) return 'Şifre en az bir büyük harf içermelidir';
if (!/[a-z]/.test(value)) return 'Şifre en az bir küçük harf içermelidir';
if (!/[0-9]/.test(value)) return 'Şifre en az bir rakam içermelidir';
return true;
}
}
};
// Şemayı koleksiyona tanımla
const users = db.collection('users').useSchema(userSchema);
// Geçerli veri ekle
try {
await users.insert({
name: 'Ayşe',
email: '[email protected]',
age: 28,
roles: ['user', 'editor'],
password: 'Secure123',
address: {
street: 'Atatürk Cad.',
city: 'İstanbul',
country: 'Türkiye'
},
birthday: new Date('1995-05-15'),
settings: {
theme: 'dark'
}
});
} catch (error) {
console.error('Doğrulama hatası:', error.message);
}Detaylı Şema Doğrulama Özellikleri
Jongle, MongoDB benzeri güçlü bir şema doğrulama sistemi sunar. Veri tiplerinin her birine özgü doğrulama seçenekleri ile verilerin istenen formatta olmasını sağlayabilirsiniz.
String Alanları
const stringSchema = {
name: {
type: 'string',
string: {
minLength: 2, // Minimum uzunluk
maxLength: 100, // Maksimum uzunluk
match: /^[a-zA-Z]+$/, // Regex deseni
enum: ['A', 'B', 'C'], // İzin verilen değerler
lowercase: true, // Küçük harfe dönüştür
uppercase: false, // Büyük harfe dönüştürme
trim: true // Baştaki ve sondaki boşlukları kaldır
}
}
}Sayı Alanları
const numberSchema = {
age: {
type: 'number',
number: {
minimum: 0, // Minimum değer
maximum: 150, // Maksimum değer
integer: true // Sadece tam sayı olmalı
}
}
}Tarih Alanları
const dateSchema = {
createdAt: {
type: 'date',
date: {
minDate: '2020-01-01', // Minimum tarih (string veya Date objesi)
maxDate: new Date() // Maksimum tarih (şu an)
}
}
}Dizi Alanları
const arraySchema = {
tags: {
type: 'array',
array: {
minItems: 1, // Minimum eleman sayısı
maxItems: 10, // Maksimum eleman sayısı
items: { // Dizi elemanlarının şeması
type: 'string',
string: {
minLength: 2
}
}
}
},
// İç içe obje dizisi
addresses: {
type: 'array',
array: {
items: {
type: 'object',
object: {
properties: {
city: { type: 'string', required: true },
country: { type: 'string', required: true }
}
}
}
}
}
}Nesne Alanları
const objectSchema = {
profile: {
type: 'object',
object: {
properties: { // İç içe alanların şeması
fullName: { type: 'string', required: true },
avatar: { type: 'string' }
}
}
}
}Şema Seçenekleri
const userSchema: SchemaDefinition = {
// Genel şema seçenekleri
strict: true, // Şemada bulunmayan alanlar reddedilir
timestamps: true, // createdAt ve updatedAt alanları otomatik eklenir
// Alanlar...
name: { type: 'string' }
// ...
};Dönüşümler ve Özel Doğrulama
const transformSchema = {
url: {
type: 'string',
// Dönüşüm fonksiyonu
transform: (value) => value.toLowerCase(),
// Özel doğrulama
validate: (value) => {
if (!value.startsWith('http')) {
return 'URL http veya https ile başlamalıdır';
}
return true; // Doğrulama başarılı
}
}
}Referanslar (İlişkiler)
const postSchema = {
title: { type: 'string' },
author: {
type: 'string',
ref: 'users' // users koleksiyonuna referans
}
}Sorgulama Örnekleri
// Temel sorgular
const users = db.collection('users');
// Basit eşitlik sorgusu
const activeUsers = await users.find({ active: true });
// Karşılaştırma operatörleri
const experiencedUsers = await users.find({
age: { $gt: 30 },
registrationDate: { $lt: new Date('2023-01-01') }
});
// Mantıksal operatörler
const results = await users.find({
$or: [
{ role: 'admin' },
{ permissions: { $in: ['manage_users', 'edit_content'] } }
],
$and: [
{ active: true },
{ lastLogin: { $gt: new Date('2023-06-01') } }
]
});
// Düzenli ifadeler
const usersWithGmail = await users.find({
email: { $regex: /@gmail\.com$/ }
});
// Sorgu ayarları
const paginatedUsers = await users.find(
{ active: true },
{
sort: { createdAt: -1 }, // En yeniden eskiye
skip: 10, // 10 kayıt atla (sayfa 2)
limit: 10, // Sayfa başına 10 kayıt
projection: { name: 1, email: 1, _id: 1 } // Sadece bu alanları getir
}
);Toplu İşlemler (Aggregation)
// Örnek veri analizi
const orderStats = await db.collection('orders').aggregate([
// Sadece tamamlanan siparişleri filtrele
{ $match: { status: 'completed' } },
// Kullanıcı ID'sine göre grupla
{ $group: {
_id: '$userId',
totalOrders: { $sum: 1 },
totalSpent: { $sum: '$amount' },
avgOrderValue: { $avg: '$amount' },
firstOrder: { $min: '$createdAt' },
lastOrder: { $max: '$createdAt' }
}},
// Toplam harcamaya göre sırala
{ $sort: { totalSpent: -1 } },
// İlk 10 müşteriyi al
{ $limit: 10 }
]);Şifreleme
// Veritabanını şifrele
await db.encrypt('güçlü-şifre-123');
// Veritabanı şifresini çöz
await db.decrypt('güçlü-şifre-123');
// Şifrelenmiş veritabanına bağlan
const db = new Jongle({
path: './secure-database',
encryption: {
enabled: true,
key: 'güçlü-şifre-123'
}
});Yedekleme ve Geri Yükleme
// Manuel yedek alma
await db.backup('./backups/manual-backup');
// Otomatik yedeklemeleri yapılandır
const db = new Jongle({
path: './my-database',
autoBackup: {
enabled: true,
interval: 24 * 60 * 60 * 1000, // 24 saat
maxBackups: 7, // Son 7 yedeği sakla
path: './auto-backups'
}
});
// Yedekten geri yükle
await db.restore('./backups/manual-backup', {
clearExisting: true // Mevcut verileri temizle
});Transaction Kullanımı
const result = await db.transaction(async (session) => {
const users = session.collection('users');
const accounts = session.collection('accounts');
// İki koleksiyonda da değişiklik yap
const userId = await users.insert({ name: 'Yeni Kullanıcı' });
await accounts.insert({ userId, balance: 1000 });
return { userId };
});Node.js'de Kullanım
Jongle, TypeScript ile yazılmış olmasına rağmen, Node.js'de JavaScript kullanarak da rahatlıkla kullanılabilir.
Kurulum
# NPM ile kurulum
npm install jongle
# Veya Yarn ile kurulum
yarn add jongleJavaScript ile Kullanım Örneği
const { Jongle } = require('jongle');
// Async/await kullanımı için ana fonksiyon
async function main() {
// Veritabanı oluştur
const db = new Jongle({
path: './veritabanim',
debug: true
});
try {
// Bağlantıyı kur
await db.connect();
console.log('Veritabanına bağlandı');
// Koleksiyonlar ile çalışma
const users = db.collection('users');
const products = db.collection('products');
// Veri ekleme
const userId = await users.insert({
ad: 'Mehmet',
soyad: 'Yılmaz',
yas: 35,
aktif: true,
kayitTarihi: new Date()
});
console.log(`Kullanıcı eklendi: ${userId}`);
// Ürün ekleme
const productIds = await products.insertMany([
{ ad: 'Laptop', fiyat: 15000, stok: 10 },
{ ad: 'Telefon', fiyat: 8000, stok: 25 },
{ ad: 'Tablet', fiyat: 5000, stok: 8 }
]);
console.log(`${productIds.length} ürün eklendi`);
// Veri sorgulama
const allUsers = await users.find();
console.log('Tüm kullanıcılar:', allUsers);
// Filtreli sorgu
const availableProducts = await products.find({
stok: { $gt: 0 },
fiyat: { $lt: 10000 }
});
console.log('Uygun fiyatlı ürünler:', availableProducts);
// Veri güncelleme
await users.update(userId, {
yas: 36,
sonGiris: new Date()
}, { partialUpdate: true });
// Veri silme
await products.deleteMany({ stok: 0 });
// Hesaplama işlemleri
const stats = await products.aggregate([
{ $match: { stok: { $gt: 5 } } },
{ $group: {
_id: null,
toplamUrun: { $sum: 1 },
ortalamaFiyat: { $avg: '$fiyat' },
toplamStok: { $sum: '$stok' }
}}
]);
console.log('Ürün istatistikleri:', stats);
// Bağlantıyı kapat
await db.close();
console.log('Veritabanı bağlantısı kapatıldı');
} catch (error) {
console.error('Hata:', error);
await db.close();
}
}
// Ana fonksiyonu çalıştır
main();Detaylı Veri Silme Örnekleri (Node.js)
const { Jongle } = require('jongle');
async function silmeOrnekleri() {
const db = new Jongle({
path: './veritabanim',
debug: true
});
try {
await db.connect();
const users = db.collection('users');
const products = db.collection('products');
const logs = db.collection('logs');
// 1. Tekil kayıt silme
const userId = 'abc123'; // Var olan bir kullanıcı ID'si
const silmeSonucu = await users.delete(userId);
console.log(`Kullanıcı silindi mi: ${silmeSonucu}`);
// 2. Çoklu kayıt silme - filtreli
// Stok değeri 0 olan tüm ürünleri sil
const silinenUrunSayisi = await products.deleteMany({
stok: 0
});
console.log(`${silinenUrunSayisi} adet sıfır stoklu ürün silindi`);
// 3. Tarih bazlı silme
// 30 günden eski logları sil
const birAyOnce = new Date();
birAyOnce.setDate(birAyOnce.getDate() - 30);
const silinenLogSayisi = await logs.deleteMany({
tarih: { $lt: birAyOnce }
});
console.log(`${silinenLogSayisi} adet eski log kaydı silindi`);
// 4. İşlem içinde ilişkili veri silme
await db.transaction(async (session) => {
const txUsers = session.collection('users');
const txOrders = session.collection('orders');
// Belirli bir kullanıcıyı ve siparişlerini sil
const userToDelete = 'user456';
// Önce kullanıcının siparişlerini sil
const silinenSiparisler = await txOrders.deleteMany({
kullaniciId: userToDelete
});
console.log(`${silinenSiparisler} adet sipariş silindi`);
// Sonra kullanıcıyı sil
await txUsers.delete(userToDelete);
console.log(`Kullanıcı silindi: ${userToDelete}`);
});
// 5. Yumuşak silme (soft delete)
// Silmek yerine aktif durumunu değiştir
await users.update('user789', {
aktif: false,
silinmeTarihi: new Date()
}, { partialUpdate: true });
console.log('Kullanıcı pasif duruma getirildi (yumuşak silme)');
// 6. Koleksiyon silme
if (await db.hasCollection('gecici_veriler')) {
await db.dropCollection('gecici_veriler');
console.log('Geçici veriler koleksiyonu silindi');
}
// 7. Belirli bir değere sahip kayıtları toplu silme
// "test" rolüne sahip kullanıcıları sil
const silinenTestKullanicilari = await users.deleteMany({
rol: 'test'
});
console.log(`${silinenTestKullanicilari} adet test kullanıcısı silindi`);
// 8. Koleksiyonu boşaltma (tüm dokümanları silme)
await logs.drop();
console.log('Logs koleksiyonu tamamen boşaltıldı');
// Bağlantıyı kapat
await db.close();
} catch (error) {
console.error('Hata:', error);
await db.close();
}
}
silmeOrnekleri().catch(console.error);CommonJS ve ES Modules Desteği
Jongle, hem CommonJS hem de ES Modules formatlarını destekler:
CommonJS (require)
const { Jongle } = require('jongle');
const db = new Jongle();ES Modules (import)
import { Jongle } from 'jongle';
const db = new Jongle();Express.js ile Kullanım Örneği
const express = require('express');
const { Jongle } = require('jongle');
const app = express();
const PORT = process.env.PORT || 3000;
// JSON veri desteği
app.use(express.json());
// Veritabanı bağlantısı
const db = new Jongle({ path: './api-database' });
// Uygulama başlatma
async function startServer() {
try {
// Veritabanına bağlan
await db.connect();
console.log('Veritabanına başarıyla bağlandı');
// Ürünler koleksiyonu
const products = db.collection('products');
// Tüm ürünleri getir
app.get('/api/products', async (req, res) => {
try {
const allProducts = await products.find();
res.json(allProducts);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// ID'ye göre ürün getir
app.get('/api/products/:id', async (req, res) => {
try {
const product = await products.findById(req.params.id);
if (!product) {
return res.status(404).json({ error: 'Ürün bulunamadı' });
}
res.json(product);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Yeni ürün ekle
app.post('/api/products', async (req, res) => {
try {
const productId = await products.insert(req.body);
const newProduct = await products.findById(productId);
res.status(201).json(newProduct);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Ürün güncelle
app.put('/api/products/:id', async (req, res) => {
try {
const success = await products.update(req.params.id, req.body);
if (!success) {
return res.status(404).json({ error: 'Ürün bulunamadı' });
}
const updatedProduct = await products.findById(req.params.id);
res.json(updatedProduct);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Ürün sil
app.delete('/api/products/:id', async (req, res) => {
try {
const success = await products.delete(req.params.id);
if (!success) {
return res.status(404).json({ error: 'Ürün bulunamadı' });
}
res.status(204).end();
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Sunucuyu başlat
app.listen(PORT, () => {
console.log(`Sunucu ${PORT} portunda çalışıyor`);
});
} catch (error) {
console.error('Sunucu başlatılamadı:', error);
process.exit(1);
}
}
// Uygulamayı başlat
startServer();Konfigürasyon Seçenekleri
const db = new Jongle({
// Temel seçenekler
path: './path/to/database', // Veritabanı dosyalarının konumu
debug: true, // Hata ayıklama modu
// Otomatik yedekleme
autoBackup: {
enabled: true, // Otomatik yedekleme etkinleştir
interval: 12 * 60 * 60 * 1000, // 12 saatte bir yedekle
maxBackups: 10, // Maksimum 10 yedek tut
path: './database-backups' // Yedeklerin konumu
},
// Şifreleme
encryption: {
enabled: true, // Şifrelemeyi etkinleştir
key: 'my-secret-key' // Şifreleme anahtarı
},
// Sıkıştırma
compression: {
enabled: true, // Sıkıştırmayı etkinleştir
level: 6 // Sıkıştırma seviyesi (1-9)
},
// Performans
performance: {
cacheSize: 5000, // Maksimum önbellek boyutu
indexStrategy: 'eager', // Eager: Hemen indeksle, Lazy: Gerektiğinde indeksle
maxConcurrentOperations: 20 // Eşzamanlı maksimum işlem sayısı
}
});Lisans
MIT
Yapımcı
m9dloff tarafından geliştirilmiştir.
Performans Optimizasyonları
Jongle 1.2.0 sürümü ile birlikte çok önemli performans iyileştirmeleri eklenmiştir. Bu özellikler sayesinde veri işleme hızı önemli ölçüde artırılmıştır.
Hızlı Mod Kullanımı
import { Jongle } from 'jongle';
const db = new Jongle({
path: './high-performance-db',
// Performans odaklı ayarlar
performance: {
cacheSize: 10000, // Önbellek boyutu (sorgu sonuçları için)
inMemoryMode: true, // Bellek içi mod (daha az disk I/O)
useBatchOperations: true, // Toplu işlemler (daha hızlı yazma)
batchSize: 500, // Toplu işlem boyutu
optimizeQueries: true, // Sorgu optimizasyonu
indexStrategy: 'eager' // Proaktif indeksleme
}
});
await db.connect();
// Veya bağlantıdan sonra performans modunu etkinleştir
db.enablePerformanceMode();
// Maksimum performans için (veri güvenliği riski taşır!)
// db.enableMaxPerformanceMode();
// Performans istatistiklerini görüntüle
const stats = await db.getPerformanceStats();
console.log(stats);İndeksler ile Sorgulama Hızını Artırma
// Sık sorgulanan alanlarda indeks oluştur
const users = db.collection('users');
await users.createIndex('email');
await users.createIndex(['age', 'country']);
// İndeksli sorgu - çok daha hızlı çalışır
const result = await users.find({ email: '[email protected]' });Önbellekleme Stratejileri
// Aynı sorguları tekrar tekrar çalıştırırken önbellek kullanılır
// İlk sorgu yavaş, sonrakiler çok hızlı
const query = { active: true, age: { $gt: 30 } };
// İlk çağrı - veritabanından okur
const firstCall = await users.find(query);
// İkinci çağrı - önbellekten döner (100x daha hızlı)
const secondCall = await users.find(query);
// Önbelleği temizle (veri değiştiğinde veya önbellek çok büyüdüğünde)
db.clearAllCaches();Toplu İşlemler
// Toplu veri ekleme - tekli eklemeden çok daha hızlı
const newUsers = Array.from({ length: 10000 }, (_, i) => ({
name: `User ${i}`,
email: `user${i}@example.com`,
age: 20 + Math.floor(Math.random() * 50)
}));
// Tek seferde ekle - toplu iş modunda çalışır
const ids = await users.insertMany(newUsers);
console.log(`${ids.length} kullanıcı eklendi`);Performans Karşılaştırması
Jongle 1.1.0, önceki sürümlere göre önemli performans artışları sağlar:
| İşlem | Jongle 1.0.0 | Jongle 1.1.0 | Fark | |-------|--------------|--------------|------| | 10k kayıt okuma | 250ms | 45ms | ~5.5x hızlı | | 10k kayıt yazma | 600ms | 120ms | ~5x hızlı | | Karmaşık sorgu | 180ms | 25ms | ~7x hızlı | | İndeksli sorgu | 85ms | 5ms | ~17x hızlı | | Bellek kullanımı | Yüksek | Optimize | ~40% daha az |
Performans İpuçları
- İndeksleri akıllıca kullanın: Sık sorgulanan alanlar için indeks oluşturun, ancak çok fazla indeks oluşturmaktan kaçının.
- Bellek içi modu gerektiğinde kullanın: Çok sık yazma işlemi olmayan senaryolarda hızı artırır.
- Sorgu önbelleği boyutunu uygulamanıza göre ayarlayın: Bellek sınırlarınıza göre optimize edin.
- Toplu işlemleri kullanın: Mümkün olduğunca tekli işlemler yerine toplu işlemler kullanın.
- Şema alanlarını sınırlayın: Sadece gereken alanları tanımlayın, gereksiz alanlardan kaçının.
- Projeksiyon kullanın: Sadece ihtiyaç duyulan alanları getirin, büyük belgeler için bellek kullanımını azaltır.
