Database Ops · 2 of 6

insert

Append a document to a collection. Returns the inserted id.

Signature

insert(collection, document)

Simple insert

proc add_log(level, msg) {
    insert("logs", {level: level, msg: msg, ts: "now"})
    return {ok: true}
}

Capture the inserted id

proc create_post(author_id, title, body) {
    let id = insert("posts", {
        author_id: author_id, title: title, body: body, likes: 0
    })
    return {created: true, post_id: id}
}

Insert with computed fields

proc charge(account_id, amount) {
    let acc = find_one("accounts", {_id: account_id})
    insert("ledger", {
        account_id: account_id,
        amount: amount,
        balance_before: acc.balance,
        balance_after: acc.balance - amount,
        type: "charge"
    })
    update("accounts", {_id: account_id}, {$inc: {balance: -amount}})
    return {ok: true}
}

Insert into multiple collections

proc signup(email, name) {
    insert("users", {email: email, name: name})
    insert("audit_log", {action: "signup", target: email})
    insert("notifications", {to: email, kind: "welcome", status: "queued"})
    return {ok: true}
}

Insert in a loop (batch)

proc bulk_seed(items) {
    for i in items {
        insert("products", {sku: i.sku, name: i.name, price: i.price, stock: i.stock})
    }
    return {inserted: count("products")}
}

Pass an array as the items parameter:

{"cmd": "call_procedure", "name": "bulk_seed",
 "params": {"items": [
    {"sku": "A", "name": "Apple", "price": 1, "stock": 100},
    {"sku": "B", "name": "Banana", "price": 2, "stock": 50}
]}}

Conditional insert (idempotent create)

proc ensure_user(email) {
    let existing = find_one("users", {email: email})
    if existing != null {
        return {created: false, user: existing}
    }
    let id = insert("users", {email: email, signups: 1})
    return {created: true, user_id: id}
}

Insert with nested document

proc record_event(user_id, kind, payload) {
    insert("events", {
        user_id: user_id,
        kind: kind,
        payload: payload,
        meta: {source: "oxiscript", version: "1"}
    })
    return {ok: true}
}
Tip: If you insert the same document many times, create a unique index on the dedupe field — let the engine reject duplicates instead of doing a find_one+insert dance.
Report Issue