MongoDBCollection
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
| Parameter | Type | Description |
|---|---|---|
document | table | Document 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)
| Parameter | Type | Description |
|---|---|---|
document | table | Document to insert |
callback | function | function(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
| Parameter | Type | Description |
|---|---|---|
documents | table | Array 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
| Parameter | Type | Description |
|---|---|---|
filter | table | Query filter ({} for all) |
limit | number | (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)
| Parameter | Type | Description |
|---|---|---|
filter | table | Query filter ({} for all) |
limit | number | Max documents to return (required — pass 0 to return nothing or nil to get unlimited documents) |
callback | function | function(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
| Parameter | Type | Description |
|---|---|---|
filter | table | Query 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
| Parameter | Type | Description |
|---|---|---|
filter | table | Query 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
| Parameter | Type | Description |
|---|---|---|
filter | table | Query filter |
update | table | Update operations |
upsert | boolean | (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
| Parameter | Type | Description |
|---|---|---|
filter | table | Query 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
| Parameter | Type | Description |
|---|---|---|
pipeline | table | Array 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
| Parameter | Type | Description |
|---|---|---|
keys | table | Index keys (1 = asc, -1 = desc) |
unique | boolean | Enforce uniqueness |
name | string | Index 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
| Parameter | Type | Description |
|---|---|---|
name | string | Index 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
| Method | Sync | Async | Description |
|---|---|---|---|
InsertOne | ✓ | ✓ | Insert single document |
InsertMany | ✓ | ✓ | Insert multiple documents |
Find | ✓ | ✓ | Find documents |
FindOne | ✓ | ✓ | Find first document |
Count | ✓ | ✓ | Count documents |
UpdateOne | ✓ | ✓ | Update first match |
UpdateMany | ✓ | ✓ | Update all matches |
DeleteOne | ✓ | ✓ | Delete first match |
DeleteMany | ✓ | ✓ | Delete all matches |
Aggregate | ✓ | ✓ | Run aggregation |
CreateIndex | ✓ | - | Create index |
ListIndexes | ✓ | - | List indexes |
DropIndex | ✓ | - | Drop index |