Utilities

API Reference

Complete API documentation for gmsv_mongo

MongoDB Global

Global functions available after require("mongo").

MongoDB.Client

Create a MongoDB client connection.

local client = MongoDB.Client(connectionString)

Parameters:

  • connectionString (string): MongoDB connection URI

Returns:

  • Client object or nil on failure

Example:

local client = MongoDB.Client("mongodb://localhost:27017")

MongoDB.ClientWithOptions

Create a MongoDB client with custom options.

local client = MongoDB.ClientWithOptions(connectionString, options)

Parameters:

  • connectionString (string): MongoDB connection URI
  • options (table): Connection options

Options:

OptionTypeDescriptionDefault
app_namestringApplication name in logs-
max_pool_sizenumberMaximum connections100
min_pool_sizenumberMinimum connections0
retry_writesbooleanRetry failed writestrue
retry_readsbooleanRetry failed readstrue
server_selection_timeoutnumberServer selection timeout (seconds)30
connect_timeoutnumberConnection timeout (seconds)10

Returns:

  • Client object or nil on failure

Example:

local client = MongoDB.ClientWithOptions("mongodb://localhost:27017", {
    app_name = "MyGModServer",
    max_pool_size = 50,
    retry_writes = true
})

MongoDB.Version

Get the module version.

local version = MongoDB.Version()

Returns:

  • string: Version number (e.g., "2.0.0")

Example:

print("gmsv_mongo version:", MongoDB.Version())

MongoDB.SuppressMessages

Toggle message suppression.

MongoDB.SuppressMessages(suppress)

Parameters:

  • suppress (boolean): True to suppress messages, false to show

Example:

MongoDB.SuppressMessages(true)  -- Suppress info messages

Client Object

Methods available on Client objects.

client:Database

Get a database reference.

local database = client:Database(name)

Parameters:

  • name (string): Database name

Returns:

  • Database object

Example:

local db = client:Database("gameserver")

client:ListDatabases

List all databases on the server.

local databases = client:ListDatabases()

Returns:

  • table: Array of database names

Example:

local dbs = client:ListDatabases()
for i, name in ipairs(dbs) do
    print(i .. ". " .. name)
end

Database Object

Methods available on Database objects.

database:Collection

Get a collection reference.

local collection = database:Collection(name)

Parameters:

  • name (string): Collection name

Returns:

  • Collection object

Example:

local players = db:Collection("players")

database:ListCollections

List all collections in the database.

local collections = database:ListCollections()

Returns:

  • table: Array of collection names

Example:

local cols = db:ListCollections()
for i, name in ipairs(cols) do
    print(i .. ". " .. name)
end

database:CreateCollection

Create a new collection.

local success = database:CreateCollection(name)

Parameters:

  • name (string): Collection name

Returns:

  • boolean: True if successful

Example:

local created = db:CreateCollection("new_collection")

Collections are created automatically when you first insert data. This method is rarely needed.


database:DropCollection

Drop (delete) a collection and all its documents.

local success = database:DropCollection(name)

Parameters:

  • name (string): Collection name

Returns:

  • boolean: True if successful

Example:

local dropped = db:DropCollection("old_collection")

database:Stats

Get collection statistics.

local stats = database:Stats(collectionName)

Parameters:

  • collectionName (string): Collection name

Returns:

  • table: Statistics object

Example:

local stats = db:Stats("players")
if stats then
    print("Documents:", stats.count)
    print("Size:", stats.size, "bytes")
end

database:Drop

Drop (delete) the entire database.

local success = database:Drop()

Returns:

  • boolean: True if successful

Example:

-- ⚠️ DANGER: Deletes all data
local dropped = testDB:Drop()

Collection Object

Methods available on Collection objects.

CRUD Operations

collection:InsertOne

Insert a single document.

local id = collection:InsertOne(document)

Parameters:

  • document (table): Document to insert

Returns:

  • string: Inserted document's ID

Example:

local id = players:InsertOne({
    steamid = "STEAM_0:1:12345",
    username = "Player1",
    level = 1
})

collection:InsertMany

Insert multiple documents.

local ids = collection:InsertMany(documents)

Parameters:

  • documents (table): Array of documents

Returns:

  • table: Array of inserted document IDs

Example:

local ids = players:InsertMany({
    { username = "Player1", level = 1 },
    { username = "Player2", level = 2 },
    { username = "Player3", level = 3 }
})

collection:Find

Find multiple documents.

local documents = collection:Find(filter, limit)

Parameters:

  • filter (table): Query filter
  • limit (number, optional): Maximum documents to return

Returns:

  • table: Array of matching documents

Example:

local results = players:Find({ level = { ["$gte"] = 10 } }, 20)

collection:FindOne

Find a single document.

local document = collection:FindOne(filter)

Parameters:

  • filter (table): Query filter

Returns:

  • table: First matching document, or nil

Example:

local player = players:FindOne({ steamid = "STEAM_0:1:12345" })

collection:UpdateOne

Update a single document.

local count = collection:UpdateOne(filter, update, upsert)

Parameters:

  • filter (table): Query filter
  • update (table): Update operations
  • upsert (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
)

collection:UpdateMany

Update multiple documents.

local count = collection:UpdateMany(filter, update, upsert)

Parameters:

  • filter (table): Query filter
  • update (table): Update operations
  • upsert (boolean, optional): Create if none match (default: false)

Returns:

  • number: Number of documents modified

Example:

local updated = players:UpdateMany(
    { active = true },
    { ["$inc"] = { bonus_credits = 100 } }
)

collection:DeleteOne

Delete a single document.

local count = collection:DeleteOne(filter)

Parameters:

  • filter (table): Query filter

Returns:

  • number: Number of documents deleted (0 or 1)

Example:

local deleted = players:DeleteOne({ steamid = "STEAM_0:1:12345" })

collection:DeleteMany

Delete multiple documents.

local count = collection:DeleteMany(filter)

Parameters:

  • filter (table): Query filter

Returns:

  • number: Number of documents deleted

Example:

local deleted = logs:DeleteMany({
    created_at = { ["$lt"] = os.time() - (30 * 24 * 60 * 60) }
})

collection:Count

Count matching documents.

local count = collection:Count(filter)

Parameters:

  • filter (table): Query filter

Returns:

  • number: Count of matching documents

Example:

local total = players:Count({})
local active = players:Count({ active = true })

Advanced Operations

collection:Aggregate

Run an aggregation pipeline.

local results = collection:Aggregate(pipeline)

Parameters:

  • pipeline (table): Array of aggregation stages

Returns:

  • table: Array of result documents

Example:

local stats = players:Aggregate({
    {
        ["$group"] = {
            _id = "$rank",
            count = { ["$sum"] = 1 },
            avgLevel = { ["$avg"] = "$level" }
        }
    },
    {
        ["$sort"] = { count = -1 }
    }
})

collection:CreateIndex

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 uniqueness
  • name (string, optional): Index name

Returns:

  • string: Index name

Example:

-- Simple index
players:CreateIndex({ steamid = 1 }, true, "steamid_unique")

-- Compound index
players:CreateIndex({ level = -1, score = -1 }, false, "level_score")

collection:ListIndexes

List all indexes on the collection.

local indexes = collection:ListIndexes()

Returns:

  • table: Array of index information

Example:

local indexes = players:ListIndexes()
for i, index in ipairs(indexes) do
    print(index.name)
end

collection:DropIndex

Drop an index.

local success = collection:DropIndex(name)

Parameters:

  • name (string): Index name

Returns:

  • boolean: True if successful

Example:

local dropped = players:DropIndex("old_index")

Query Operators

Comparison

OperatorDescriptionExample
$eqEqual{ field = value }
$neNot equal{ field = { ["$ne"] = value } }
$gtGreater than{ field = { ["$gt"] = value } }
$gteGreater than or equal{ field = { ["$gte"] = value } }
$ltLess than{ field = { ["$lt"] = value } }
$lteLess than or equal{ field = { ["$lte"] = value } }
$inIn array{ field = { ["$in"] = {1, 2, 3} } }
$ninNot in array{ field = { ["$nin"] = {1, 2} } }

Logical

OperatorDescriptionExample
$andLogical AND (implicit){ field1 = val1, field2 = val2 }
$orLogical OR{ ["$or"] = { {f1 = v1}, {f2 = v2} } }
$notLogical NOT{ field = { ["$not"] = { ["$gt"] = 5 } } }
$norLogical NOR{ ["$nor"] = { {f1 = v1}, {f2 = v2} } }

Element

OperatorDescriptionExample
$existsField exists{ field = { ["$exists"] = true } }
$typeField type{ field = { ["$type"] = "string" } }

String

OperatorDescriptionExample
$regexRegex match{ field = { ["$regex"] = "pattern" } }

Update Operators

Field

OperatorDescriptionExample
$setSet field value{ ["$set"] = { field = value } }
$unsetRemove field{ ["$unset"] = { field = "" } }
$renameRename field{ ["$rename"] = { old = "new" } }
$setOnInsertSet only on insert (with upsert){ ["$setOnInsert"] = { field = value } }
$currentDateSet to current date{ ["$currentDate"] = { field = true } }

Numeric

OperatorDescriptionExample
$incIncrement{ ["$inc"] = { field = amount } }
$mulMultiply{ ["$mul"] = { field = multiplier } }
$minSet to minimum{ ["$min"] = { field = value } }
$maxSet to maximum{ ["$max"] = { field = value } }

Array

OperatorDescriptionExample
$pushAdd to array{ ["$push"] = { arr = value } }
$pullRemove from array{ ["$pull"] = { arr = value } }
$popRemove first/last{ ["$pop"] = { arr = -1 } } (-1=first, 1=last)
$addToSetAdd if unique{ ["$addToSet"] = { arr = value } }

Aggregation Operators

Pipeline Stages

StageDescription
$matchFilter documents
$groupGroup by field(s)
$sortSort documents
$projectSelect/exclude fields
$limitLimit results
$skipSkip documents
$countCount documents
$lookupJoin collections

Accumulator Operators (in $group)

OperatorDescription
$sumSum values
$avgAverage values
$minMinimum value
$maxMaximum value
$firstFirst value
$lastLast value
$pushCreate array