mongodb 7.5.0MongoG Script Globals, BSON, and Execution Modes
Use MongoG's real driver globals, database helpers, BSON constructors, console output, Query Mode restrictions, and Trusted Script Mode allowlist.
Real driver objects are already available
MongoG creates one official MongoClient per active connection runtime and places real driver values in the script context. You do not import a wrapper API or wait for per-method IPC support.
The primary globals are:
client: the connectedMongoClient.db: the active driverDbobject.mongodb: the officialmongodbmodule namespace.bson: the officialbsonmodule namespace.use(name): change the active database and updatedb.print(),printjson(), andconsole: emit structured console output.
print("Client type:", client.constructor.name);
print("Database:", db.databaseName);
print("Driver Db type:", db instanceof mongodb.Db);
const analytics = client.db("mongog_tutorial");
analytics.collection("events").find({ type: "page-view" });
MongoG also supplies a getSiblingDB(name) helper on its db values for familiar cross-database scripts.
BSON constructors
Common shell-style constructors create genuine BSON values:
const values = {
objectId: ObjectId(),
date: ISODate(),
int32: NumberInt(12),
long: NumberLong("9007199254740993"),
double: Double(12.5),
decimal: NumberDecimal("19.99"),
uuid: UUID(),
expression: BSONRegExp("^mongo", "i"),
minimum: MinKey(),
maximum: MaxKey(),
};
printjson(values);
Aliases such as Int32, Long, and Decimal128 are also available. Advanced constructors include BinData, Timestamp, DBRef, Code, and BSONSymbol. Prefer the simplest type that accurately represents the domain.
The module namespaces remain available when you want their explicit forms:
const id = new bson.ObjectId();
const decimal = bson.Decimal128.fromString("42.10");
printjson({ id, decimal });
Query Mode
Query Mode is designed for normal database work. It provides the driver context but blocks root access to process and module features including process, require, module, Buffer, network APIs, timers, and dynamic or static imports.
// Works in Query Mode: no import is required.
const sessions = db.collection("sessions");
sessions.find({ expiresAt: { $gt: ISODate() } });
The VM controls scope and generated-code features, but it is not claimed as an operating-system security boundary. Run scripts you understand and enforce database permissions with MongoDB roles.
Trusted Script Mode
Trusted Script Mode requires explicit consent. It adds an allowlisted require() for only the bundled driver modules:
const { ObjectId } = require("mongodb");
const { Decimal128 } = require("bson");
printjson({
id: new ObjectId(),
price: Decimal128.fromString("29.50"),
});
Arbitrary packages, file-system modules, and other Node built-ins are not added. Trusted mode is not a way to install dependencies or bypass MongoDB authorization.
Console output limits
Console arguments are serialized as Extended JSON and attached to the current statement. Output is bounded so an accidental logging loop cannot grow the renderer indefinitely. Use a query result for large datasets and print only summaries.
const count = db.collection("events").countDocuments({ type: "page-view" });
console.info("Matching events", { count });
Work across databases explicitly
use() changes the active db binding for following statements. When one workflow needs two databases at once, keep explicit Db references instead of repeatedly switching global context:
const appDb = client.db("mongog_tutorial");
const adminDb = client.db("admin");
print("Application database:", appDb.databaseName);
print("Administration database:", adminDb.databaseName);
appDb.collection("events").find({ type: "page-view" });
Access still depends on the MongoDB user’s roles. Obtaining a Db object does not grant permission and does not create the database.
Inspect exported classes and constants
The mongodb namespace exposes the same classes, errors, enums, and helpers bundled with the product. This is useful for precise error handling:
try {
await db.collection("unique_items").insertOne({ _id: "duplicate" });
} catch (error) {
if (error instanceof mongodb.MongoServerError && error.code === 11000) {
print("Duplicate key detected");
} else {
throw error;
}
}
Do not catch only by message text. Driver error classes and server codes communicate intent more reliably, while unknown failures should be rethrown.
Choose the least powerful mode
Use Query Mode for routine work, shared scripts, and database investigations. Switch to Trusted Script Mode only when the script genuinely needs the allowlisted CommonJS module form and you understand its source.
Practice by printing the constructor names for client, db, a collection, ObjectId, and Decimal128. Then reproduce the BSON values once with globals and once through bson. Confirm that both forms produce the same BSON classes.
Common mistakes
- Importing
MongoClientin Query Mode is unnecessary; the connectedclientalready exists. - Expecting Trusted Script Mode to load any npm package ignores its strict
mongodbandbsonallowlist. - Comparing a stored
ObjectIdto its hexadecimal string does not match BSON types. - Printing thousands of documents is less useful than returning a cursor and using the result viewer.
- Catching errors by message text alone is fragile; prefer driver classes and documented server codes.
- Switching the global database repeatedly in a multi-database workflow is harder to review than named
Dbreferences.
Continue learning
Finish with cursors, result paging, and cancellation. For concepts and class signatures, consult the official Node.js driver documentation and 7.5 API reference.