mongo

The mongo module is a MongoDB client. connect returns an integer handle (or -1 on failure) that you pass to every other call. Documents are ordinary Langoost objects; BSON values map to Langoost values and ObjectIds are hex-stringified. Import it with import mongo.

Object literals accept string-literal keys, which is what makes Mongo operators read naturally: {"$set": {status: "active"}}.

Connection

FunctionSignatureDescription
connectmongo.connect(uri: string) → intconnect using a standard MongoDB URI; returns a handle, -1 on failure
closemongo.close(handle: int) → booldisconnect and free the handle

Documents

FunctionSignatureDescription
insertOnemongo.insertOne(handle: int, db: string, coll: string, doc: object) → stringinsert one document; returns the inserted id
insertManymongo.insertMany(handle: int, db: string, coll: string, docs: object[]) → intinsert many; returns the count inserted
findmongo.find(handle: int, db: string, coll: string, filter: object) → object[]return all matching documents
findOnemongo.findOne(handle: int, db: string, coll: string, filter: object) → objectreturn the first match, or nil
updateOnemongo.updateOne(handle: int, db: string, coll: string, filter: object, update: object) → intupdate one; returns the modified count
deleteOnemongo.deleteOne(handle: int, db: string, coll: string, filter: object) → intdelete one; returns the deleted count
countmongo.count(handle: int, db: string, coll: string, filter: object) → intcount matching documents

Example

import mongo

let db = mongo.connect("mongodb://localhost:27017")
if db == -1 {
    println("connection failed")
    exit(1)
}

mongo.insertOne(db, "shop", "users", {name: "alice", active: true})

let users = mongo.find(db, "shop", "users", {active: true})
for u in users {
    println(u.name)
}

mongo.updateOne(db, "shop", "users",
    {name: "alice"},
    {"$set": {active: false}})

println(mongo.count(db, "shop", "users", {}))
mongo.close(db)
Standard library · View as Markdown · llms-full.txt