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
| Function | Signature | Description |
|---|---|---|
connect | mongo.connect(uri: string) → int | connect using a standard MongoDB URI; returns a handle, -1 on failure |
close | mongo.close(handle: int) → bool | disconnect and free the handle |
Documents
| Function | Signature | Description |
|---|---|---|
insertOne | mongo.insertOne(handle: int, db: string, coll: string, doc: object) → string | insert one document; returns the inserted id |
insertMany | mongo.insertMany(handle: int, db: string, coll: string, docs: object[]) → int | insert many; returns the count inserted |
find | mongo.find(handle: int, db: string, coll: string, filter: object) → object[] | return all matching documents |
findOne | mongo.findOne(handle: int, db: string, coll: string, filter: object) → object | return the first match, or nil |
updateOne | mongo.updateOne(handle: int, db: string, coll: string, filter: object, update: object) → int | update one; returns the modified count |
deleteOne | mongo.deleteOne(handle: int, db: string, coll: string, filter: object) → int | delete one; returns the deleted count |
count | mongo.count(handle: int, db: string, coll: string, filter: object) → int | count 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)