CRUD Operations

Complete guide to Create, Read, Update, and Delete operations in NexaDB.

Quick Reference - All Query Operators

Comparison
$eq - Equal
$ne - Not equal
$gt - Greater than
$gte - Greater or equal
$lt - Less than
$lte - Less or equal
Array & Logic
$in - In array
$nin - Not in array
$all - Contains all
$and - All match
$or - Any match
$not - Negate
String & Field
$regex - Pattern match
$text - Full-text
$exists - Field exists
$size - Array size

Create Documents

JavaScript
const { NexaClient } = require('nexaclient');
const db = new NexaClient({
  host: 'localhost', port: 6970,
  username: 'root', password: 'nexadb123'
});
await db.connect();

// Create in default database
const user = await db.create('users', {
  name: 'Alice',
  email: 'alice@example.com',
  age: 28,
  tags: ['developer', 'javascript']
});

// Create in specific database
await db.create('analytics', 'events', {
  type: 'signup',
  user_id: user.document_id
});
Python
from nexaclient import NexaClient

client = NexaClient(
    host='localhost', port=6970,
    username='root', password='nexadb123'
)
client.connect()

# Create in default database
user = client.create('users', {
    'name': 'Alice',
    'email': 'alice@example.com',
    'age': 28,
    'tags': ['developer', 'python']
})

# Create in specific database
client.create('analytics', 'events', {
    'type': 'signup',
    'user_id': user['document_id']
})
CLI (nexa)
nexa(default)> use users
āœ“ Switched to collection 'users'

nexa(default:users)> create {"name": "Alice", "email": "alice@example.com", "age": 28}
āœ“ Document created: doc_abc123

# Create in different database
nexa(default:users)> use_db analytics
āœ“ Switched to database 'analytics'

nexa(analytics)> use events
āœ“ Switched to collection 'events'

nexa(analytics:events)> create {"type": "signup", "user_id": "doc_abc123"}
āœ“ Document created: doc_def456

Read Documents

JavaScript - Get by ID
// Get single document by ID
const user = await db.read('users', 'doc_123');

// Query with filters
const adults = await db.query('users', {
  age: { $gte: 18 }
}, {
  limit: 10,
  sort: { age: -1 }
});

// Count documents
const count = await db.count('users', {
  status: 'active'
});
Python - Get by ID
# Get single document by ID
user = client.read('users', 'doc_123')

# Query with filters
adults = client.query('users', {
    'age': {'$gte': 18}
}, {
    'limit': 10,
    'sort': {'age': -1}
})

# Count documents
count = client.count('users', {
    'status': 'active'
})
CLI - Query Examples
nexa(default:users)> query {}
āœ“ Found 150 document(s)

nexa(default:users)> query {"age": {"$gte": 18}}
āœ“ Found 125 document(s)

nexa(default:users)> query {"status": "active", "age": {"$gte": 21, "$lte": 35}}
āœ“ Found 45 document(s)

nexa(default:users)> count {"status": "active"}
āœ“ Document count: 125

Update Documents

JavaScript
// Update a document
const updated = await db.update(
  'users',
  'doc_123',
  {
    age: 29,
    lastLogin: Date.now(),
    status: 'active'
  }
);

// Partial update (merge)
await db.update('users', 'doc_123', {
  profile: { verified: true }
});
Python
# Update a document
updated = client.update(
    'users',
    'doc_123',
    {
        'age': 29,
        'last_login': time.time(),
        'status': 'active'
    }
)

# Partial update (merge)
client.update('users', 'doc_123', {
    'profile': {'verified': True}
})
CLI
nexa(default:users)> update doc_123 {"age": 29, "status": "active"}
āœ“ Document updated: doc_123

nexa(default:users)> update doc_456 {"profile": {"verified": true}}
āœ“ Document updated: doc_456

Delete Documents

JavaScript
// Delete a single document
await db.delete('users', 'doc_123');

// Delete from specific database
await db.delete('analytics', 'events', 'evt_456');

// Query then delete
const inactive = await db.query('users', {
  lastLogin: { $lt: Date.now() - 90*24*60*60*1000 }
});
for (const user of inactive) {
  await db.delete('users', user._id);
}
Python
# Delete a single document
client.delete('users', 'doc_123')

# Delete from specific database
client.delete('analytics', 'events', 'evt_456')

# Query then delete
import time
cutoff = time.time() - 90*24*60*60
inactive = client.query('users', {
    'last_login': {'$lt': cutoff}
})
for user in inactive:
    client.delete('users', user['_id'])
CLI
nexa(default:users)> delete doc_123
āœ“ Document deleted: doc_123

# Query to find documents, then delete
nexa(default:users)> query {"status": "inactive"}
āœ“ Found 3 document(s):
[1] {"_id": "doc_abc", ...}
[2] {"_id": "doc_def", ...}
[3] {"_id": "doc_ghi", ...}

nexa(default:users)> delete doc_abc
āœ“ Document deleted: doc_abc

Query Operators

Comparison Operators

$eq

Equal to

{ age: { $eq: 25 } }
$ne

Not equal to

{ status: { $ne: 'deleted' } }
$gt / $gte

Greater than / Greater than or equal

{ age: { $gte: 18 } }
$lt / $lte

Less than / Less than or equal

{ price: { $lte: 100 } }

Array Operators

$in

Value in array

{ status: { $in: ['active', 'pending', 'verified'] } }
$nin

Value not in array

{ status: { $nin: ['deleted', 'banned'] } }
$all

Array contains all values

{ tags: { $all: ['javascript', 'react'] } }

Logical Operators

$and - All conditions must be true
// Find users between 18 and 65
await db.query('users', {
  $and: [
    { age: { $gte: 18 } },
    { age: { $lte: 65 } }
  ]
});
$or - Any condition can be true
// Find users who are admins OR moderators
await db.query('users', {
  $or: [
    { role: 'admin' },
    { role: 'moderator' }
  ]
});
$not - Negates a condition
// Find users NOT between 18 and 65
await db.query('users', {
  age: { $not: { $gte: 18, $lte: 65 } }
});

String Operators

$regex - Pattern matching
// Find emails ending with @gmail.com
await db.query('users', {
  email: { $regex: '.*@gmail\.com$' }
});

// Case-insensitive search
await db.query('users', {
  name: { $regex: 'john', $options: 'i' }
});
$text - Full-text search
// Full-text search (requires fulltext index)
await db.query('articles', {
  $text: { $search: 'machine learning AI' }
});

Existence & Type Operators

$exists - Check field existence
// Find users with phone numbers
await db.query('users', {
  phone: { $exists: true }
});

// Find users WITHOUT phone numbers
await db.query('users', {
  phone: { $exists: false }
});

Complex Nested Queries

Combine multiple conditions
// Find active premium users aged 25-45
await db.query('users', {
  $and: [
    { status: 'active' },
    { plan: 'premium' },
    { age: { $gte: 25, $lte: 45 } }
  ]
});
Advanced OR with nested AND
// Premium users OR active trial users
await db.query('users', {
  $or: [
    { plan: 'premium' },
    {
      $and: [
        { plan: 'trial' },
        { status: 'active' }
      ]
    }
  ]
});
Range query with exclusions
// Products priced 50-200, excluding 'electronics'
await db.query('products', {
  $and: [
    { price: { $gte: 50, $lte: 200 } },
    { category: { $ne: 'electronics' } },
    { stock: { $gt: 0 } }
  ]
});

Sorting & Pagination

Sort and limit results
// Get top 10 highest-paid users
await db.query('users',
  { status: 'active' },
  {
    sort: { salary: -1 },  // -1 = descending
    limit: 10
  }
);

// Sort by multiple fields
await db.query('users',
  { status: 'active' },
  {
    sort: { created_at: -1, name: 1 },  // 1 = ascending
    limit: 20
  }
);
Pagination with skip and limit
// Page 1 (items 0-19)
await db.query('users', {}, { skip: 0, limit: 20 });

// Page 2 (items 20-39)
await db.query('users', {}, { skip: 20, limit: 20 });

// Page 3 (items 40-59)
await db.query('users', {}, { skip: 40, limit: 20 });

Real-World Query Examples

E-commerce: Find discounted products
// Active products with >20% discount, in stock
await db.query('products', {
  $and: [
    { status: 'active' },
    { discount: { $gte: 20 } },
    { stock: { $gt: 0 } },
    { price: { $lte: 500 } }
  ]
}, {
  sort: { discount: -1 },
  limit: 50
});
Social: Find recommended users
// Users with 100+ followers, active in last 30 days
await db.query('users', {
  $and: [
    { follower_count: { $gte: 100 } },
    { last_active: { $gte: Date.now() - 30*24*60*60*1000 } },
    { account_status: 'verified' },
    { tags: { $in: ['developer', 'designer', 'creator'] } }
  ]
}, {
  sort: { follower_count: -1 },
  limit: 20
});
Analytics: Find high-value customers
// Customers with >$1000 lifetime value, 5+ orders
await db.query('customers', {
  $and: [
    { lifetime_value: { $gte: 1000 } },
    { order_count: { $gte: 5 } },
    { churn_risk: { $lte: 0.3 } },
    { $or: [
      { plan: 'premium' },
      { referral_count: { $gte: 3 } }
    ]}
  ]
}, {
  sort: { lifetime_value: -1 },
  limit: 100
});

āœ“ Fast with Indexes

Create indexes on frequently queried fields (age, status, price, created_at) to make these queries 100-200x faster! See the Indexing Guide to learn more.