Database Ops · 3 of 6

update / update_one

Modify documents in place. update changes every match; update_one stops after the first.

Signatures

update(collection, query, modification)
update_one(collection, query, modification)

$set — overwrite or add fields

proc rename(id, name) {
    update("users", {_id: id}, {$set: {name: name}})
    return {ok: true}
}

$inc — atomic increment / decrement

proc credit(account_id, amount) {
    update("accounts", {_id: account_id}, {$inc: {balance: amount}})
    return {ok: true}
}

proc debit(account_id, amount) {
    update("accounts", {_id: account_id}, {$inc: {balance: -amount}})
    return {ok: true}
}

$unset — remove a field

proc clear_phone(id) {
    update("users", {_id: id}, {$unset: {phone: ""}})
    return {ok: true}
}

$push — append to an array

proc add_tag(id, tag) {
    update("posts", {_id: id}, {$push: {tags: tag}})
    return {ok: true}
}

$pull — remove array elements matching query

proc remove_tag(id, tag) {
    update("posts", {_id: id}, {$pull: {tags: tag}})
    return {ok: true}
}

$addToSet — push only if not present

proc follow(user_id, followee) {
    update("users", {_id: user_id}, {$addToSet: {following: followee}})
    update("users", {_id: followee}, {$addToSet: {followers: user_id}})
    return {ok: true}
}

Combined operators (recommended)

Combine all field changes for the same document into a single call. The OCC validator checks document versions, not field versions.

proc place_order(account_id, sku, qty, price) {
    update("accounts", {_id: account_id}, {
        $inc: {balance: -(qty * price), order_count: 1, total_spent: qty * price},
        $set: {last_order_at: "now"},
        $push: {recent_orders: sku}
    })
    update("products", {sku: sku}, {$inc: {stock: -qty, sold: qty}})
    return {ok: true}
}

Dot-notation for nested fields

proc move_user(id, new_city) {
    update("users", {_id: id}, {$set: {"address.city": new_city}})
    return {ok: true}
}

update across many docs

proc archive_inactive(days_old) {
    update("users", {last_seen_days: {$gte: days_old}}, {$set: {archived: true}})
    return {archived: count("users", {archived: true})}
}

update_one for "first match wins"

proc consume_token(user_id) {
    update_one("tokens", {user_id: user_id, used: false}, {
        $set: {used: true, used_at: "now"}
    })
    return {ok: true}
}
OCC rule: Multiple update calls on the same document in one procedure will conflict on commit. Always merge them into a single update with combined operators.
Report Issue