Browse documentation
aner.db · Connector

MongoDB connections

Read and write native BSON documents with verified TLS, private credentials and bounded canonical Extended JSON results.

Part of aner.db, the native database module. The module reference covers shared credentials, connection lifetime, result conversion and all four connectors.

aner.db.mongodb sends native BSON requests through the MongoDB C driver and BSON library. It preserves document types as canonical Extended JSON and shares the aner.db connection and result lifecycle. See the database overview and Credentials.

Requirements and private credentials

Use a compatible installed Aner executable with optional MongoDB support and its native client runtime. db.available("mongodb") reports support in the executable. Connecting performs a native ping so network, authentication and TLS failures surface immediately.

sh
aner secrets set demo-mongodb-password --store system
aner secrets status demo-mongodb-password --store system

The hidden prompt keeps the value outside source. Use secrets.stored("demo-mongodb-password"), or inject ANER_MONGODB_PASSWORD privately and select secrets.env("ANER_MONGODB_PASSWORD"). Linux system storage is unavailable. The explicit POSIX file store pairs --store file with secrets.file and retains plaintext with owner only permissions. Read the Credentials guide before choosing a store. The connection requires a SecretRef, never a password String.

Connect with verified TLS

All settings below are fictional and should be replaced privately:

aner
import aner.db;
import aner.db.mongodb;
import aner.secrets;

let connection: DBConnection = mongodb.connect(
    host: "db.example.invalid", port: 27017, database: "example_science",
    user: "example_reader", password: secrets.stored("demo-mongodb-password"),
    auth_database: "admin", tls: true, timeout_seconds: 10);
print(db.connected(connection));
db.close(connection);

auth_database is where the account was created and can differ from the database queried. The factory accepts one DNS hostname, IPv4 address or IPv6 literal and a separate port. URI strings, multiple hosts, SRV records, Unix sockets and URI options are outside this initial API. An IPv6 literal can be ::1 or [::1].

TLS defaults to true and verifies the certificate and hostname. For a private CA, set ANER_DB_MONGODB_CA privately to a PEM CA bundle path. There is no certificate verification bypass. Use tls: false only for a deliberately trusted local development service without TLS.

The timeout defaults to 10 seconds and accepts 1 through 300. It configures native connection, server selection and socket timeouts per stage rather than a single query wall clock deadline. db.connected performs a ping. Copies share a session; operations serialize and closing one invalidates all aliases. Use separate connections for independent concurrent work.

Find native documents

Use an active connection to select a bounded result:

aner
let samples: DBResult = mongodb.find(connection, "aner_demo_samples",
    "{\"label\":2}",
    options_json: "{\"projection\":{\"_id\":0},\"sort\":{\"feature_a\":1}}",
    max_documents: 1000, max_bytes: 1048576);
print(db.rows(samples));
for index in Range(db.rows(samples)) {
    print(mongodb.document(samples, index));
}

Filter and options inputs must each be exactly one JSON object. The native BSON parser accepts ordinary JSON and Extended JSON. It rejects root arrays, concatenated objects, invalid JSON, embedded NUL, excessive nesting and inputs larger than 64 MiB. Build allowed query fields and operators deliberately. Use a JSON serializer for untrusted strings instead of concatenation.

Options include projection, sort, skip, limit, batchSize and maxTimeMS. Explicit limit and singleBatch retain MongoDB semantics. Enabled tailable, awaitData, exhaust and allowPartialResults options reject; streaming and change streams remain future work.

Each result row has one String column named document. mongodb.document(result, index) equals db.text(result, index, 0). Canonical Extended JSON preserves ObjectId, Int64, date, decimal, binary and nested values. A numeric field can appear as {"$numberInt":"2"} or {"$numberLong":"2"}. db.to_table produces document strings; it does not flatten fields or create a numeric feature tensor. Transform numeric attributes explicitly before training.

Default limits are 100000 documents and 67108864 retained bytes. The native cursor reads batches; overflow returns no partial result, destroys the cursor and keeps the connection usable. Native batches and temporary serialization consume additional memory. Reduce work with indexed filters, projection, batchSize and server maxTimeMS.

Insert samples and run commands

These fragments need an active connection with appropriate permissions:

aner
print(mongodb.insert_one(connection, "aner_demo_samples",
    "{\"feature_a\":1.2,\"feature_b\":2.3,\"feature_c\":3.4,\"label\":0}"));
print(mongodb.command(connection, "{\"ping\":1}", max_bytes: 4096));

insert_one returns 1 after an acknowledged native insert. MongoDB generates _id when absent. The complete source appends four synthetic documents with three numeric attributes and labels 0 through 3, then reads them and converts the JSON strings to a DataTable. Every run appends another four documents, so use a dedicated demo collection and an account permitted to write there.

sh
aner check examples/db_mongodb.aner
aner run examples/db_mongodb.aner

Checking opens no connection. Running connects and performs the documented writes. command can perform database writes and administration actions according to the account's permissions. It returns the raw canonical Extended JSON reply and does not issue getMore for command cursors. Prefer find for collection reads.

A command's byte cap is checked after the native server reply and temporary serialization. A successful write remains applied if the response later exceeds the cap or is lost. Review native retry and write semantics before repeating a command with side effects.

Diagnostics retain fixed operation names and numeric domain/code values, excluding native server and parser messages that can contain private values. Native unstructured logging is disabled when Aner initializes MongoDB, with client structured logging disabled when supported. The native driver retains authentication state until the session closes; Aner wipes its temporary resolved password after setup. Keep private settings and document content out of public logs and notebooks.

Native references: MongoDB C driver, TLS configuration and canonical Extended JSON.

Aner documentation · Reference and guides