Developer Guide ​
A comprehensive overview of Singlebase's core capabilities powered by BaseQL - our unified query language for all operations.
Overview ​
Singlebase provides a complete backend platform with powerful querying, data transformation, and AI capabilities. All operations use BaseQL, a MongoDB-inspired language with cleaner syntax that works across your entire backend.
Core APIs ​
Document Database ​
NoSQL JSON storage with powerful querying and filtering.
Operations: db.find, db.insert, db.update, db.upsert, db.delete, db.archive, db.restore, db.count
Key features:
- Real-time CRUD operations
- Advanced filtering with operators
- Pagination and sorting
- Lookups (joins)
- Output expressions
- Data operators for transformations
Users & Auth ​
Complete user authentication and management.
Operations: auth.signup, auth.signin, auth.signout, auth.update_profile, auth.update_account, auth.send_otp, auth.refresh_token
Key features:
- Email/password authentication
- Passwordless (OTP) sign-in
- JWT token management
- Profile management
- Role-based access
File Storage ​
Secure file uploads with automatic image processing.
Operations: file.get, file.update, file.delete, file.presign_upload, file.finalize_upload, file.report_upload_failure
Key features:
- Presigned URL uploads
- Automatic image variants
- Public/private access control
- Metadata management
Vector Database ​
AI-powered semantic search with automatic embeddings.
Operations: vdb.insert, vdb.search, vdb.delete
Key features:
- Semantic similarity search
- Automatic embedding generation
- Smart content chunking
- Multi-language support
BaseAI ​
Intelligent text processing and generation.
Operations: baseai.create, baseai.summarize, baseai.categorize, baseai.analyze_sentiment, baseai.extract_entities, baseai.translate, baseai.vectorize
Key features:
- Content generation
- Sentiment analysis
- Text categorization
- Entity extraction
- Language translation
Filter Operators ​
Match and query documents in filter object. Use :$operator syntax.
Comparison Operators ​
json
{
"age:$eq": 25,
"age:$ne": 30,
"age:$gt": 18,
"age:$gte": 21,
"age:$lt": 65,
"age:$lte": 60
}$eq- Equal to$ne- Not equal to$gt- Greater than$gte- Greater than or equal$lt- Less than$lte- Less than or equal
Array Operators ​
json
{
"status:$in": ["active", "pending"],
"status:$nin": ["deleted", "banned"],
"tags:$includes": "featured",
"tags:$nincludes": "draft",
"tags:$all": ["sale", "clearance"],
"tags:$any": ["new", "trending"],
"tags:$none": ["spam", "hidden"]
}$in- Field value in array$nin- Field value not in array$includes- Array field includes value$nincludes- Array field doesn't include value$all- Array field contains all values$any- Array field contains any value$none- Array field contains none
Range & Logical Operators ​
json
{
"price:$between": [10, 100],
"$or": [
{ "status": "active" },
{ "role": "admin" }
],
"$nor": [
{ "status": "deleted" },
{ "status": "archived" }
]
}$between- Value in range (inclusive)$or- At least one condition matches$nor- No conditions match$and- All conditions match (implicit)
Data Operators ​
Transform and modify data in data object. Use :$operator syntax.
Basic Operations ​
json
{
"name:$set": "John Doe",
"score:$incr": 10,
"credits:$decr": 5
}$set- Set value$replace- Replace value$incr- Increment number$decr- Decrement number
Date/Time Operations ​
json
{
"created_at:$now": true,
"updated_at:$datetime": true,
"timestamp:$timestamp": true
}$now- Current datetime$datetime- Current datetime (alias)$timestamp- Current Unix timestamp
ID Generation ​
json
{
"tracking_id:$uuid": true,
"order_id:$uuid4": true,
"event_id:$uuid7": true
}$uuid- UUID4 without dashes$uuid4- UUID4 with dashes$uuid7- Time-ordered UUID7
Data Operations ​
json
{
"old_field:$rename": "new_field",
"source:$copy": "destination",
"count:$length": "items"
}$rename- Move/rename field$copy- Copy field$length- Get length
List Operations ​
json
{
"tags:$push": "featured",
"notifications:$lpush": { "msg": "New update" },
"tags:$extend": ["sale", "clearance"],
"history:$lextend": [{"action": "created"}],
"roles:$addset": ["editor", "contributor"],
"queue:$pop": true,
"queue:$lpop": true,
"tags:$remove": "draft",
"items:$clear": true
}$push- Add to end$lpush- Add to front$extend- Append multiple items$lextend- Prepend multiple items$addset- Add unique items$pop- Remove from end$lpop- Remove from front$remove- Remove matching items$clear- Remove all items
Template Expressions ​
Dynamic data transformation using expressions. Used in both Data Operators and Output Expressions.
Expression Types ​
json
{
"greeting": "Hello {{ name }}!",
"total": "?{{ price * quantity }}",
"$full_name": "first_name + ' ' + last_name"
}{{ expr }}- String template (returns string)?{{ expr }}- Native evaluation (returns original type)$field- Shorthand for?
String Interpolation ​
json
{
"message": "User {{ name }} has {{ points }} points",
"summary": "Order #{{ order_id }} - {{ item_count }} items"
}Calculations ​
json
{
"tax": "?{{ subtotal * 0.08 }}",
"total": "?{{ subtotal + tax }}",
"is_eligible": "?{{ age >= 18 && verified }}"
}Conditional Expressions ​
json
{
"status": "{{ age >= 18 ? 'adult' : 'minor' }}",
"discount": "?{{ is_member ? 0.2 : 0.1 }}"
}Helper Functions ​
Built-in functions for data transformation. Prefixed with @ and used within template expressions.
Date & Time ​
json
{
"now": "{{ @now() }}",
"formatted": "{{ @formatdate(created_at, 'YYYY-MM-DD') }}",
"future": "{{ @shiftdate(@now(), '+7days') }}",
"diff": "?{{ @diffdates(end_date, start_date, 'days') }}"
}@now()- Current datetime@formatdate(dt, format)- Format date@shiftdate(date, shift)- Shift date@timestamp()- Current timestamp@diffdates(d1, d2, unit)- Date difference
ID Generation ​
json
{
"id": "{{ @uuid4() }}",
"tracking": "{{ @uuid() }}",
"code": "{{ @shortid() }}"
}@uuid()- UUID without dashes@uuid4()- UUID with dashes@uuid7()- Time-ordered UUID@shortid()- Short 8-char ID@hash(text)- SHA-256 hash
String Functions ​
json
{
"upper": "{{ @uppercase(name) }}",
"lower": "{{ @lowercase(email) }}",
"title": "{{ @titlecase(text) }}",
"slug": "{{ @slugify(title) }}",
"masked": "{{ @maskstr(card, 4) }}",
"combined": "{{ @concat(first, ' ', last) }}"
}@uppercase(text)- Convert to uppercase@lowercase(text)- Convert to lowercase@titlecase(text)- Title case@capitalize(text)- Capitalize first letter@slugify(text)- URL-friendly slug@trim(text)- Remove whitespace@len(value)- Get length@concat(...)- Concatenate values@replace(text, old, new)- Replace text@substring(text, start, end)- Extract substring@maskstr(text, visible, char)- Mask string
Number Functions ​
json
{
"currency": "{{ @tocurrency(99.99, 'USD') }}",
"percent": "{{ @topercent(0.15, 2) }}",
"formatted": "{{ @tonumber(1234567, 0) }}",
"random": "?{{ @random(1, 100) }}"
}@tocurrency(amount, curr)- Format currency@topercent(value, decimals)- Format percentage@tonumber(value, decimals)- Format with separators@toint(value, default)- Convert to integer@tofloat(value, default)- Convert to float@abs(x)- Absolute value@round(x)- Round number@floor(x)- Round down@random(min, max)- Random number
Collection Functions ​
json
{
"total": "?{{ @sum(prices) }}",
"average": "?{{ @avg(scores) }}",
"highest": "?{{ @max(values) }}",
"lowest": "?{{ @min(values) }}"
}@sum(array)- Sum values@avg(array)- Average@min(array)- Minimum@max(array)- Maximum@sortby(array, key, rev)- Sort array@groupby(array, key)- Group array@unique(array, key)- Unique values
Validation ​
json
{
"valid_email": "?{{ @isemail(email) }}",
"valid_url": "?{{ @isurl(website) }}",
"is_empty": "?{{ @isempty(field) }}"
}@isemail(value)- Validate email@isurl(value)- Validate URL@isempty(value)- Check if empty@isnull(value)- Check if null
Output Expressions ​
Reshape query results in output object using template expressions.
Basic Output ​
json
{
"op": "db.find",
"collection": "users",
"output": {
"$name": "name",
"$email": "email",
"display": "{{ name }} ({{ email }})"
}
}Calculated Fields ​
json
{
"output": {
"$name": "name",
"age_next_year": "?{{ age + 1 }}",
"is_adult": "?{{ age >= 18 }}",
"$item_count": "@len(items)"
}
}Array Mapping ​
json
{
"output": {
"$name": "name",
"orders:$map(orders)": {
"$total": "total",
"formatted": "{{ @tocurrency(total, 'USD') }}",
"is_large": "?{{ total > 100 }}"
}
}
}Field Selection ​
Select specific fields:
json
{
"output": "{name, email, age}"
}Exclude fields:
json
{
"output": "!{password, ssn, internal_notes}"
}Select all fields:
json
{
"output": "**"
}Extend all fields:
json
{
"output": {
"_": "**",
"$fullname": "first_name + ' ' + last_name",
"location": "{{ address.street }}, {{ address.city }}, {{ address.zip_code }}"
}
}Rename fields:
json
{
"output": "{myNewName:name, myNewEmail:email, age}"
}Pagination ​
Control result size and navigate through large datasets.
Using limit/offset:
json
{
"op": "db.find",
"collection": "products",
"limit": 50,
"offset": 0
}Using page/per_page:
json
{
"op": "db.find",
"collection": "products",
"page": 1,
"per_page": 50
}Response includes:
json
{
"data": [...],
"meta": {
"pagination": {
"page": 1,
"per_page": 50,
"total_pages": 10,
"size": 500,
"has_next": true,
"next_page": 2
}
}
}Lookup Expressions ​
Join collections during queries using aliased lookups.
json
{
"op": "db.find",
"collection": "orders",
"lookup": {
"user": {
"collection": "users",
"on": "user_id",
"limit": 1
}
}
}Result:
json
{
"_key": "order_123",
"user_id": "user_456",
"total": 99.99,
"__refs__": {
"user": [
{
"_key": "user_456",
"name": "John Doe",
"email": "john@example.com"
}
]
}
}Multiple lookups:
json
{
"lookup": {
"user": {
"collection": "users",
"on": "user_id = users._key"
},
"products": {
"collection": "products",
"on": "_key"
}
}
}Nested lookups:
json
{
"lookup": {
"user": {
"collection": "users",
"on": "user_id = users._key",
"lookup": {
"address": {
"collection": "addresses",
"on": "$parent._key = addresses.user_id"
}
}
}
}
}Sorting ​
Sort results by one or more fields.
json
{
"op": "db.find",
"collection": "products",
"sort": "price asc"
}Multiple fields:
json
{
"sort": "category asc, price desc"
}Nested fields:
json
{
"sort": "user.profile.age desc"
}Rate Limits ​
Read operations: 1,000 requests/minute
db.find,db.count,file.get,vdb.search
Write operations: 500 requests/minute
db.insert,db.update,db.delete,file.presign_upload,baseai.*
Response headers:
http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 847
X-RateLimit-Reset: 1705651200Complete Examples ​
User Registration & Profile Update ​
json
{
"op": "auth.signup",
"email": "user@example.com",
"password": "SecurePass123",
"display_name": "John Doe"
}json
{
"op": "db.update",
"collection": "users",
"filter": { "email": "user@example.com" },
"data": {
"last_login:$now": true,
"login_count:$incr": 1,
"status": "active"
}
}Product Search with Filtering ​
json
{
"op": "db.find",
"collection": "products",
"filter": {
"price:$between": [10, 100],
"category:$in": ["electronics", "gadgets"],
"stock:$gt": 0,
"tags:$includes": "featured"
},
"sort": "price asc",
"limit": 20
}Order Creation with Calculations ​
json
{
"op": "db.insert",
"collection": "orders",
"data": {
"order_id:$uuid4": true,
"user_id": "user_123",
"items": [
{ "name": "Widget", "price": 29.99, "qty": 2 }
],
"$subtotal": "@sum(@map(items, 'price * qty'))",
"tax": "?{{ subtotal * 0.08 }}",
"total": "?{{ subtotal + tax }}",
"created_at:$now": true,
"status": "pending"
}
}Query with Output Formatting ​
json
{
"op": "db.find",
"collection": "users",
"filter": { "status": "active" },
"output": {
"display_name": "{{ first_name }} {{ last_name }}",
"contact": "{{ email }} | {{ phone }}",
"$age": "age",
"is_adult": "?{{ age >= 18 }}",
"member_since": "{{ @formatdate(_created_at, 'MMMM YYYY') }}",
"$order_count": "@len(orders)"
},
"limit": 50
}Semantic Search ​
json
{
"op": "vdb.insert",
"collection": "docs",
"data": [
{
"content": "Machine learning enables computers to learn from data.",
"content_type": "text",
"metadata": { "category": "AI" }
}
]
}json
{
"op": "vdb.search",
"query": "How do computers learn?",
"collection": "docs"
}AI Content Generation ​
json
{
"op": "baseai.create",
"input": "Write a product description for wireless headphones",
"content_length": 200,
"content_style": "marketing"
}Quick Reference ​
Filter Operators → Match documents in filter: { }
- Comparison:
$eq,$ne,$gt,$gte,$lt,$lte - Array:
$in,$nin,$includes,$nincludes,$all,$any,$none - Range:
$between - Logical:
$or,$nor,$and(implicit)
Data Operators → Transform data in data: { }
- Basic:
$set,$incr,$decr - Date:
$now,$timestamp - ID:
$uuid,$uuid4,$uuid7 - List:
$push,$lpush,$pop,$lpop,$extend,$lextend,$addset,$remove,$clear
Template Expressions → Dynamic values
{{ expr }}- String result?{{ expr }}- Native type result$field- Shorthand
Helper Functions → Data transformation
- Date:
@now(),@formatdate(),@shiftdate() - String:
@uppercase(),@lowercase(),@concat(),@slugify() - Number:
@tocurrency(),@round(),@random() - Collection:
@sum(),@avg(),@len() - Validation:
@isemail(),@isurl()
Output Expressions → Reshape results in output: { }
- Field mapping:
"$new_field": "old_field" - Calculations:
"total": "?NaN" - Array mapping:
"items:$map(items)": { }