Inherited from v1.0.0

mongo module

MongoDB client backed by mongo-c-driver. Connect with a URI, drill down to db.collection, and CRUD with plain maps. Method names mirror the official MongoDB drivers (camelCase) so the API feels familiar.

import "mongo" as mongo;

var client = mongo.connect("mongodb://localhost:27017");
var users  = client.db("myapp").collection("users");

users.insertOne({ name: "Alice", roles: ["admin"] });
var alice = users.findOne({ name: "Alice" });
print(alice.roles[0]);                 // admin

users.updateOne({ name: "Alice" }, { "$set": { roles: ["admin", "editor"] } });
users.deleteOne({ name: "Alice" });

client.close();

Module API

FunctionDescription
mongo.connect(uri) → clientParse and connect. URI like mongodb://user:pass@host:port/?authSource=....
mongo.version() → stringmongo-c-driver client version.

Client / db / collection

StepDescription
client.db(name)Pick a database. Returns {collection(name), drop(), ...}.
client.collection(db_name, coll_name)Shortcut for client.db(d).collection(c).
client.ping(db_name?)Force a handshake (defaults to admin). Throws on failure.
client.close()Drop the connection.
db.collection(name)Pick a collection.
db.drop()Drop the whole database.

Collection methods

MethodReturnsDescription
coll.find(filter, opts?)list of mapsAll matching docs. opts may set limit, skip, sort, projection.
coll.findOne(filter)map | nullFirst matching doc, or null.
coll.insertOne(doc){acknowledged, insertedId}Single insert. Generates _id if missing.
coll.insertMany(docs){acknowledged, insertedCount, insertedIds}Bulk insert.
coll.updateOne(filter, update)mongoc reply map$set-style update.
coll.deleteOne(filter){deletedCount}Delete first match.
coll.deleteMany(filter){deletedCount}Delete every match. Pass {} to wipe.
coll.countDocuments(filter?)numberServer-side count. Filter defaults to {}.
coll.distinct(field, filter?)listUnique values of field.
coll.aggregate(pipeline, opts?)list of mapsRun an aggregation pipeline.
coll.drop()nullDrop the collection.

Examples

// find with options
var top10 = users.find(
    { status: "active" },
    {
        projection: { name: 1, email: 1, _id: 0 },
        sort:       { created_at: -1 },
        limit:      10
    }
);

// operators are quoted because of the leading $
var adults = users.find({ age: { "$gte": 18 } });

// bulk insert
var r = users.insertMany([
    { name: "A", age: 21 },
    { name: "B", age: 35 }
]);
print(r.insertedCount);   // 2

// distinct values
var roles = users.distinct("role");

// aggregation pipeline
var by_role = users.aggregate([
    { "$match": { status: "active" } },
    { "$group": { _id: "$role", n: { "$sum": 1 } } },
    { "$sort":  { n: -1 } }
]);

See also