Database Ops · 1 of 6

find / find_one

Read documents from a collection. find returns an array; find_one returns a single document or null.

Signatures

find(collection, query)        // → array
find_one(collection, query)    // → object or null

Find one by id

proc get_user(id) {
    let u = find_one("users", {_id: id})
    if u == null { abort "not found" }
    return u
}

Find one by indexed field

proc by_email(email) {
    return find_one("users", {email: email})
}

Find with comparison operators

proc adults() {
    return find("users", {age: {$gte: 18}})
}

proc in_range(min, max) {
    return find("users", {age: {$gte: min, $lte: max}})
}

Find with $in

proc by_emails(emails) {
    return find("users", {email: {$in: emails}})
}

Find with $or

proc admins_or_owners(team_id) {
    return find("members", {
        team_id: team_id,
        $or: [{role: "admin"}, {role: "owner"}]
    })
}

Find with regex

proc gmail_users() {
    return find("users", {email: {$regex: "@gmail\\.com$", $options: "i"}})
}

Find with $exists

proc has_phone() {
    return find("users", {phone: {$exists: true}})
}

Find on nested fields (dot path in query)

proc tokyo_users() {
    return find("users", {"address.city": "Tokyo"})
}

Empty query = all documents

proc all_users() {
    return find("users", {})
}

Use the result

proc summary() {
    let users = find("users", {active: true})
    let total_age = 0
    for u in users {
        total_age = total_age + u.age
    }
    return {n: count("users", {active: true}), total_age: total_age}
}
Heads-up: find_one always returns null when nothing matches — never {}. Always guard with if x == null { ... }.
Report Issue