API Reference

MongoDBCollection

Collection class with CRUD, aggregation, and index operations

MongoDBCollection

The MongoDBCollection class provides all operations for working with MongoDB collections, including CRUD operations, aggregation, and index management.

Insert Operations

InsertOne

Inserts a single document into the collection.

collection:InsertOne(document) → string | nil
ParameterTypeDescription
documenttableDocument to insert

Returns: Inserted document's ObjectId as string, or nil on failure

local id = collection:InsertOne({
    username = "Player1",
    level = 1,
    credits = 1000
})
print("Inserted:", id)

InsertOneAsync

Async version with callback.

collection:InsertOneAsync(document, callback)
ParameterTypeDescription
documenttableDocument to insert
callbackfunctionfunction(err, insertedId)
collection:InsertOneAsync({ name = "Test" }, function(err, id)
    if err then print("Error:", err)
    else print("Inserted:", id) end
end)

InsertMany

Inserts multiple documents.

collection:InsertMany(documents) → table | nil
ParameterTypeDescription
documentstableArray of documents

Returns: Array of inserted ObjectIds, or nil on failure

local ids = collection:InsertMany({
    { name = "Alice", level = 5 },
    { name = "Bob", level = 10 }
})
print("Inserted", #ids, "documents")

InsertManyAsync

Async version with callback.

collection:InsertManyAsync(documents, callback)

Query Operations

Find

Finds documents matching a filter.

collection:Find(filter [, limit]) → table | nil
ParameterTypeDescription
filtertableQuery filter ({} for all)
limitnumber(Optional) Max documents to return

Returns: Array of matching documents, or nil on failure

-- Find all
local all = collection:Find({})

-- Find with filter
local high = collection:Find({ level = { ["$gte"] = 10 } })

-- Find with limit
local top10 = collection:Find({}, 10)

FindAsync

Async version with callback.

collection:FindAsync(filter, limit, callback)
ParameterTypeDescription
filtertableQuery filter ({} for all)
limitnumberMax documents to return (required — pass 0 to return nothing or nil to get unlimited documents)
callbackfunctionfunction(err, documents)
limit is required. Unlike the synchronous Find, the async version expects the limit as the second argument. If it is omitted, the callback will not be called with any documents. To get all matching documents, pass nil as the limit.
-- Find up to 50 high-level players
collection:FindAsync({ level = { ["$gte"] = 10 } }, 50, function(err, docs)
    if err then print("Error:", err)
    else print("Found", #docs, "players") end
end)

FindOne

Finds the first matching document.

collection:FindOne(filter) → table | nil
ParameterTypeDescription
filtertableQuery filter

Returns: First matching document, or nil if not found

local player = collection:FindOne({ steamid = "STEAM_0:1:12345" })
if player then
    print("Found:", player.username)
end

FindOneAsync

Async version with callback.

collection:FindOneAsync(filter, callback)

Count

Counts documents matching a filter.

collection:Count(filter) → number
ParameterTypeDescription
filtertableQuery filter ({} for all)

Returns: Count of matching documents

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

CountAsync

Async version with callback.

collection:CountAsync(filter, callback)

Update Operations

UpdateOne

Updates the first matching document.

collection:UpdateOne(filter, update [, upsert]) → number
ParameterTypeDescription
filtertableQuery filter
updatetableUpdate operations
upsertboolean(Optional) Create if not exists

Returns: Number of modified documents (0 or 1)

-- Simple update
collection:UpdateOne(
    { steamid = "STEAM_0:1:12345" },
    { ["$set"] = { level = 10 } }
)

-- With upsert
collection:UpdateOne(
    { steamid = "STEAM_0:1:99999" },
    { ["$set"] = { level = 1 } },
    true  -- upsert
)

UpdateOneAsync

Async version with callback.

collection:UpdateOneAsync(filter, update, callback)

UpdateMany

Updates all matching documents.

collection:UpdateMany(filter, update [, upsert]) → number

Returns: Number of modified documents

local modified = collection:UpdateMany(
    { vip = true },
    { ["$inc"] = { bonus = 100 } }
)
print("Updated", modified, "VIP players")

UpdateManyAsync

Async version with callback.

collection:UpdateManyAsync(filter, update, callback)

Delete Operations

DeleteOne

Deletes the first matching document.

collection:DeleteOne(filter) → number
ParameterTypeDescription
filtertableQuery filter

Returns: Number of deleted documents (0 or 1)

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

DeleteOneAsync

Async version with callback.

collection:DeleteOneAsync(filter, callback)

DeleteMany

Deletes all matching documents.

collection:DeleteMany(filter) → number

Returns: Number of deleted documents

-- Delete expired
local deleted = collection:DeleteMany({
    expires_at = { ["$lt"] = os.time() }
})

-- Delete ALL (dangerous!)
collection:DeleteMany({})

DeleteManyAsync

Async version with callback.

collection:DeleteManyAsync(filter, callback)

Aggregation

Aggregate

Runs an aggregation pipeline.

collection:Aggregate(pipeline) → table | nil
ParameterTypeDescription
pipelinetableArray of aggregation stages

Returns: Array of result documents, or nil on failure

local results = collection:Aggregate({
    { ["$match"] = { active = true } },
    { ["$group"] = {
        _id = "$class",
        count = { ["$sum"] = 1 }
    }},
    { ["$sort"] = { count = -1 } }
})

AggregateAsync

Async version with callback.

collection:AggregateAsync(pipeline, callback)

Index Operations

CreateIndex

Creates an index on the collection.

collection:CreateIndex(keys, unique, name) → string | nil
ParameterTypeDescription
keystableIndex keys (1 = asc, -1 = desc)
uniquebooleanEnforce uniqueness
namestringIndex name

Returns: Created index name, or nil on failure

-- Unique index
collection:CreateIndex({ steamid = 1 }, true, "steamid_unique")

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

-- Text index
collection:CreateIndex({ username = "text" }, false, "username_text")

ListIndexes

Lists all indexes on the collection.

collection:ListIndexes() → table | nil

Returns: Array of index information documents

local indexes = collection:ListIndexes()
for _, idx in ipairs(indexes or {}) do
    print(idx.name)
end

DropIndex

Drops a specific index.

collection:DropIndex(name) → boolean
ParameterTypeDescription
namestringIndex name (or "*" for all)

Returns: true on success, false on failure

collection:DropIndex("old_index")
collection:DropIndex("*")  -- Drop all (except _id)

Callback Signature

All async methods use callbacks with this signature:

function(err, result)
    if err then
        -- Handle error (string)
    else
        -- Process result
    end
end

Method Summary

MethodSyncAsyncDescription
InsertOneInsert single document
InsertManyInsert multiple documents
FindFind documents
FindOneFind first document
CountCount documents
UpdateOneUpdate first match
UpdateManyUpdate all matches
DeleteOneDelete first match
DeleteManyDelete all matches
AggregateRun aggregation
CreateIndex-Create index
ListIndexes-List indexes
DropIndex-Drop index