Global functions available after require("mongo").
Create a MongoDB client connection.
local client = MongoDB.Client(connectionString)
Parameters:
connectionString (string): MongoDB connection URIReturns:
Client object or nil on failureExample:
local client = MongoDB.Client("mongodb://localhost:27017")
Create a MongoDB client with custom options.
local client = MongoDB.ClientWithOptions(connectionString, options)
Parameters:
connectionString (string): MongoDB connection URIoptions (table): Connection optionsOptions:
| Option | Type | Description | Default |
|---|---|---|---|
app_name | string | Application name in logs | - |
max_pool_size | number | Maximum connections | 100 |
min_pool_size | number | Minimum connections | 0 |
retry_writes | boolean | Retry failed writes | true |
retry_reads | boolean | Retry failed reads | true |
server_selection_timeout | number | Server selection timeout (seconds) | 30 |
connect_timeout | number | Connection timeout (seconds) | 10 |
Returns:
Client object or nil on failureExample:
local client = MongoDB.ClientWithOptions("mongodb://localhost:27017", {
app_name = "MyGModServer",
max_pool_size = 50,
retry_writes = true
})
Get the module version.
local version = MongoDB.Version()
Returns:
string: Version number (e.g., "2.0.0")Example:
print("gmsv_mongo version:", MongoDB.Version())
Toggle message suppression.
MongoDB.SuppressMessages(suppress)
Parameters:
suppress (boolean): True to suppress messages, false to showExample:
MongoDB.SuppressMessages(true) -- Suppress info messages
Methods available on Client objects.
Get a database reference.
local database = client:Database(name)
Parameters:
name (string): Database nameReturns:
Database objectExample:
local db = client:Database("gameserver")
List all databases on the server.
local databases = client:ListDatabases()
Returns:
table: Array of database namesExample:
local dbs = client:ListDatabases()
for i, name in ipairs(dbs) do
print(i .. ". " .. name)
end
Methods available on Database objects.
Get a collection reference.
local collection = database:Collection(name)
Parameters:
name (string): Collection nameReturns:
Collection objectExample:
local players = db:Collection("players")
List all collections in the database.
local collections = database:ListCollections()
Returns:
table: Array of collection namesExample:
local cols = db:ListCollections()
for i, name in ipairs(cols) do
print(i .. ". " .. name)
end
Create a new collection.
local success = database:CreateCollection(name)
Parameters:
name (string): Collection nameReturns:
boolean: True if successfulExample:
local created = db:CreateCollection("new_collection")
Collections are created automatically when you first insert data. This method is rarely needed.
Drop (delete) a collection and all its documents.
local success = database:DropCollection(name)
Parameters:
name (string): Collection nameReturns:
boolean: True if successfulExample:
local dropped = db:DropCollection("old_collection")
Get collection statistics.
local stats = database:Stats(collectionName)
Parameters:
collectionName (string): Collection nameReturns:
table: Statistics objectExample:
local stats = db:Stats("players")
if stats then
print("Documents:", stats.count)
print("Size:", stats.size, "bytes")
end
Drop (delete) the entire database.
local success = database:Drop()
Returns:
boolean: True if successfulExample:
-- ⚠️ DANGER: Deletes all data
local dropped = testDB:Drop()
Methods available on Collection objects.
Insert a single document.
local id = collection:InsertOne(document)
Parameters:
document (table): Document to insertReturns:
string: Inserted document's IDExample:
local id = players:InsertOne({
steamid = "STEAM_0:1:12345",
username = "Player1",
level = 1
})
Insert multiple documents.
local ids = collection:InsertMany(documents)
Parameters:
documents (table): Array of documentsReturns:
table: Array of inserted document IDsExample:
local ids = players:InsertMany({
{ username = "Player1", level = 1 },
{ username = "Player2", level = 2 },
{ username = "Player3", level = 3 }
})
Find multiple documents.
local documents = collection:Find(filter, limit)
Parameters:
filter (table): Query filterlimit (number, optional): Maximum documents to returnReturns:
table: Array of matching documentsExample:
local results = players:Find({ level = { ["$gte"] = 10 } }, 20)
Find a single document.
local document = collection:FindOne(filter)
Parameters:
filter (table): Query filterReturns:
table: First matching document, or nilExample:
local player = players:FindOne({ steamid = "STEAM_0:1:12345" })
Update a single document.
local count = collection:UpdateOne(filter, update, upsert)
Parameters:
filter (table): Query filterupdate (table): Update operationsupsert (boolean, optional): Create if doesn't exist (default: false)Returns:
number: Number of documents modified (0 or 1)Example:
local updated = players:UpdateOne(
{ steamid = "STEAM_0:1:12345" },
{ ["$set"] = { level = 10 } },
false
)
Update multiple documents.
local count = collection:UpdateMany(filter, update, upsert)
Parameters:
filter (table): Query filterupdate (table): Update operationsupsert (boolean, optional): Create if none match (default: false)Returns:
number: Number of documents modifiedExample:
local updated = players:UpdateMany(
{ active = true },
{ ["$inc"] = { bonus_credits = 100 } }
)
Delete a single document.
local count = collection:DeleteOne(filter)
Parameters:
filter (table): Query filterReturns:
number: Number of documents deleted (0 or 1)Example:
local deleted = players:DeleteOne({ steamid = "STEAM_0:1:12345" })
Delete multiple documents.
local count = collection:DeleteMany(filter)
Parameters:
filter (table): Query filterReturns:
number: Number of documents deletedExample:
local deleted = logs:DeleteMany({
created_at = { ["$lt"] = os.time() - (30 * 24 * 60 * 60) }
})
Count matching documents.
local count = collection:Count(filter)
Parameters:
filter (table): Query filterReturns:
number: Count of matching documentsExample:
local total = players:Count({})
local active = players:Count({ active = true })
Run an aggregation pipeline.
local results = collection:Aggregate(pipeline)
Parameters:
pipeline (table): Array of aggregation stagesReturns:
table: Array of result documentsExample:
local stats = players:Aggregate({
{
["$group"] = {
_id = "$rank",
count = { ["$sum"] = 1 },
avgLevel = { ["$avg"] = "$level" }
}
},
{
["$sort"] = { count = -1 }
}
})
Create an index on the collection.
local indexName = collection:CreateIndex(keys, unique, name)
Parameters:
keys (table): Fields to index (1 = ascending, -1 = descending)unique (boolean): Whether to enforce uniquenessname (string, optional): Index nameReturns:
string: Index nameExample:
-- Simple index
players:CreateIndex({ steamid = 1 }, true, "steamid_unique")
-- Compound index
players:CreateIndex({ level = -1, score = -1 }, false, "level_score")
List all indexes on the collection.
local indexes = collection:ListIndexes()
Returns:
table: Array of index informationExample:
local indexes = players:ListIndexes()
for i, index in ipairs(indexes) do
print(index.name)
end
Drop an index.
local success = collection:DropIndex(name)
Parameters:
name (string): Index nameReturns:
boolean: True if successfulExample:
local dropped = players:DropIndex("old_index")
| Operator | Description | Example |
|---|---|---|
$eq | Equal | { field = value } |
$ne | Not equal | { field = { ["$ne"] = value } } |
$gt | Greater than | { field = { ["$gt"] = value } } |
$gte | Greater than or equal | { field = { ["$gte"] = value } } |
$lt | Less than | { field = { ["$lt"] = value } } |
$lte | Less than or equal | { field = { ["$lte"] = value } } |
$in | In array | { field = { ["$in"] = {1, 2, 3} } } |
$nin | Not in array | { field = { ["$nin"] = {1, 2} } } |
| Operator | Description | Example |
|---|---|---|
$and | Logical AND (implicit) | { field1 = val1, field2 = val2 } |
$or | Logical OR | { ["$or"] = { {f1 = v1}, {f2 = v2} } } |
$not | Logical NOT | { field = { ["$not"] = { ["$gt"] = 5 } } } |
$nor | Logical NOR | { ["$nor"] = { {f1 = v1}, {f2 = v2} } } |
| Operator | Description | Example |
|---|---|---|
$exists | Field exists | { field = { ["$exists"] = true } } |
$type | Field type | { field = { ["$type"] = "string" } } |
| Operator | Description | Example |
|---|---|---|
$regex | Regex match | { field = { ["$regex"] = "pattern" } } |
| Operator | Description | Example |
|---|---|---|
$set | Set field value | { ["$set"] = { field = value } } |
$unset | Remove field | { ["$unset"] = { field = "" } } |
$rename | Rename field | { ["$rename"] = { old = "new" } } |
$setOnInsert | Set only on insert (with upsert) | { ["$setOnInsert"] = { field = value } } |
$currentDate | Set to current date | { ["$currentDate"] = { field = true } } |
| Operator | Description | Example |
|---|---|---|
$inc | Increment | { ["$inc"] = { field = amount } } |
$mul | Multiply | { ["$mul"] = { field = multiplier } } |
$min | Set to minimum | { ["$min"] = { field = value } } |
$max | Set to maximum | { ["$max"] = { field = value } } |
| Operator | Description | Example |
|---|---|---|
$push | Add to array | { ["$push"] = { arr = value } } |
$pull | Remove from array | { ["$pull"] = { arr = value } } |
$pop | Remove first/last | { ["$pop"] = { arr = -1 } } (-1=first, 1=last) |
$addToSet | Add if unique | { ["$addToSet"] = { arr = value } } |
| Stage | Description |
|---|---|
$match | Filter documents |
$group | Group by field(s) |
$sort | Sort documents |
$project | Select/exclude fields |
$limit | Limit results |
$skip | Skip documents |
$count | Count documents |
$lookup | Join collections |
| Operator | Description |
|---|---|
$sum | Sum values |
$avg | Average values |
$min | Minimum value |
$max | Maximum value |
$first | First value |
$last | Last value |
$push | Create array |