Examples
Basic Examples
Connection and simple CRUD operation examples
These examples are AI-generated and has not been reviewed for accuracy. Use them as a starting point and verify correctness before deploying in production.
Basic Examples
These examples demonstrate fundamental gmsv_mongo operations.
Connection Example
--[[
Basic Connection Example
Demonstrates how to create a MongoDB connection and verify it's working
]]
require("mongo")
-- Print module version
print("MongoDB Module Version:", MongoDB.Version())
-- Simple connection
local client = MongoDB.Client("mongodb://localhost:27017")
if not client then
print("Failed to connect to MongoDB!")
return
end
print("✓ Successfully connected to MongoDB!")
-- List all databases
local databases = client:ListDatabases()
if databases then
print("\nAvailable databases:")
for i, dbName in ipairs(databases) do
print(" " .. i .. ". " .. dbName)
end
end
-- Connection with options
local clientWithOpts = MongoDB.ClientWithOptions("mongodb://localhost:27017", {
app_name = "GModServer",
max_pool_size = 50,
retry_writes = true
})
if clientWithOpts then
print("\n✓ Successfully connected with custom options!")
end
CRUD Operations Example
--[[
CRUD Operations Example
Demonstrates Create, Read, Update, Delete operations
]]
require("mongo")
local client = MongoDB.Client("mongodb://localhost:27017")
if not client then
print("Connection failed!")
return
end
local db = client:Database("gameserver")
local players = db:Collection("players")
print("=== CRUD Operations Example ===\n")
-- CREATE: Insert a single document
print("1. INSERT ONE")
local playerId = players:InsertOne({
steamid = "STEAM_0:1:12345678",
username = "TestPlayer",
level = 1,
credits = 1000,
joined_at = os.time()
})
print(" Inserted player with ID:", playerId)
-- CREATE: Insert multiple documents
print("\n2. INSERT MANY")
local ids = players:InsertMany({
{
steamid = "STEAM_0:0:87654321",
username = "PlayerTwo",
level = 5,
credits = 5000
},
{
steamid = "STEAM_0:1:11111111",
username = "PlayerThree",
level = 10,
credits = 10000
}
})
print(" Inserted", #ids, "players")
-- READ: Find all players
print("\n3. FIND ALL")
local allPlayers = players:Find({})
print(" Total players:", #allPlayers)
for i, player in ipairs(allPlayers) do
print(" -", player.username, "Level:", player.level)
end
-- READ: Find one player
print("\n4. FIND ONE")
local player = players:FindOne({ steamid = "STEAM_0:1:12345678" })
if player then
print(" Found:", player.username)
end
-- READ: Find with filter
print("\n5. FIND WITH FILTER")
local highLevelPlayers = players:Find({ level = { ["$gte"] = 5 } })
print(" Players level 5+:", #highLevelPlayers)
-- READ: Count documents
print("\n6. COUNT")
local count = players:Count({ level = { ["$gte"] = 5 } })
print(" Count of level 5+ players:", count)
-- UPDATE: Update one document
print("\n7. UPDATE ONE")
local updated = players:UpdateOne(
{ steamid = "STEAM_0:1:12345678" },
{ ["$set"] = { level = 2, credits = 1500 } }
)
print(" Updated", updated, "document(s)")
-- UPDATE: Update many documents
print("\n8. UPDATE MANY")
local updatedMany = players:UpdateMany(
{ level = { ["$lt"] = 5 } },
{ ["$inc"] = { credits = 100 } }
)
print(" Updated", updatedMany, "document(s)")
-- DELETE: Delete one document
print("\n9. DELETE ONE")
local deleted = players:DeleteOne({ steamid = "STEAM_0:1:11111111" })
print(" Deleted", deleted, "document(s)")
-- DELETE: Delete many documents
print("\n10. DELETE MANY")
local deletedMany = players:DeleteMany({ level = { ["$lt"] = 2 } })
print(" Deleted", deletedMany, "document(s)")
print("\n=== CRUD Example Complete ===")
Async Operations Example
--[[
Async Operations Example
Demonstrates non-blocking database operations with callbacks
]]
require("mongo")
local client = MongoDB.Client("mongodb://localhost:27017")
local db = client:Database("test_db")
local collection = db:Collection("users")
print("=== Async Operations Example ===\n")
-- InsertOneAsync
print("1. InsertOneAsync")
collection:InsertOneAsync(
{ name = "John", age = 30 },
function(err, result)
if err then
print(" Error:", err)
else
print(" Inserted ID:", result)
end
end
)
-- InsertManyAsync
print("\n2. InsertManyAsync")
collection:InsertManyAsync(
{
{ name = "Alice", age = 25 },
{ name = "Bob", age = 35 }
},
function(err, results)
if err then
print(" Error:", err)
else
print(" Inserted", #results, "documents")
end
end
)
-- FindAsync
print("\n3. FindAsync")
collection:FindAsync(
{ age = { ["$gte"] = 25 } },
100,
function(err, results)
if err then
print(" Error:", err)
else
print(" Found", #results, "documents:")
for _, doc in ipairs(results) do
print(" -", doc.name, "(age:", doc.age .. ")")
end
end
end
)
-- FindOneAsync
print("\n4. FindOneAsync")
collection:FindOneAsync(
{ name = "John" },
function(err, result)
if err then
print(" Error:", err)
elseif result then
print(" Found:", result.name, "age", result.age)
else
print(" Not found")
end
end
)
-- UpdateOneAsync
print("\n5. UpdateOneAsync")
collection:UpdateOneAsync(
{ name = "John" },
{ ["$set"] = { age = 31 } },
function(err, modified)
if err then
print(" Error:", err)
else
print(" Modified", modified, "document(s)")
end
end
)
-- DeleteOneAsync
print("\n6. DeleteOneAsync")
collection:DeleteOneAsync(
{ name = "Bob" },
function(err, deleted)
if err then
print(" Error:", err)
else
print(" Deleted", deleted, "document(s)")
end
end
)
-- CountAsync
print("\n7. CountAsync")
collection:CountAsync(
{},
function(err, count)
if err then
print(" Error:", err)
else
print(" Total documents:", count)
end
end
)
Query Operators Example
--[[
Query Operators Example
Demonstrates MongoDB query operators
]]
require("mongo")
local client = MongoDB.Client("mongodb://localhost:27017")
local db = client:Database("gameserver")
local players = db:Collection("players")
-- Insert test data
players:InsertMany({
{ username = "Alice", level = 15, class = "Warrior", credits = 5000, vip = true },
{ username = "Bob", level = 8, class = "Mage", credits = 2000, vip = false },
{ username = "Charlie", level = 25, class = "Warrior", credits = 15000, vip = true },
{ username = "Diana", level = 12, class = "Rogue", credits = 3500, vip = false },
{ username = "Eve", level = 30, class = "Mage", credits = 20000, vip = true }
})
print("=== Query Operators Example ===\n")
-- Comparison operators
print("1. Level > 10:")
local results = players:Find({ level = { ["$gt"] = 10 } })
for _, p in ipairs(results) do print(" -", p.username, "Level:", p.level) end
print("\n2. Level between 10 and 20:")
results = players:Find({ level = { ["$gte"] = 10, ["$lte"] = 20 } })
for _, p in ipairs(results) do print(" -", p.username, "Level:", p.level) end
-- Array operators
print("\n3. Class in [Warrior, Mage]:")
results = players:Find({ class = { ["$in"] = { "Warrior", "Mage" } } })
for _, p in ipairs(results) do print(" -", p.username, "Class:", p.class) end
-- Logical operators
print("\n4. VIP OR level >= 20:")
results = players:Find({
["$or"] = {
{ vip = true },
{ level = { ["$gte"] = 20 } }
}
})
for _, p in ipairs(results) do
print(" -", p.username, "VIP:", tostring(p.vip), "Level:", p.level)
end
print("\n5. Warriors with level >= 15:")
results = players:Find({
class = "Warrior",
level = { ["$gte"] = 15 }
})
for _, p in ipairs(results) do print(" -", p.username) end
-- Count with filter
print("\n6. Count VIP players:")
local vipCount = players:Count({ vip = true })
print(" VIP count:", vipCount)
print("\n=== Query Operators Complete ===")
Error Handling Example
--[[
Error Handling Example
Demonstrates proper error handling patterns
]]
require("mongo")
-- Connection error handling
local function safeConnect(uri)
local client = MongoDB.Client(uri)
if not client then
print("ERROR: Failed to connect to MongoDB")
print("Please check:")
print(" - MongoDB server is running")
print(" - Connection string is correct")
print(" - Network allows the connection")
return nil
end
return client
end
local client = safeConnect("mongodb://localhost:27017")
if not client then return end
local db = client:Database("test")
local collection = db:Collection("test")
-- Sync operation error handling
local function safeInsert(col, doc)
local success, result = pcall(function()
return col:InsertOne(doc)
end)
if not success then
print("Insert error:", result)
return nil
end
return result
end
local id = safeInsert(collection, { test = true })
if id then
print("Inserted:", id)
end
-- Async error handling
collection:FindOneAsync({ test = true }, function(err, result)
if err then
print("Query failed:", err)
return
end
if result then
print("Found document")
else
print("No document found")
end
end)
-- Validation before operations
local function validatePlayer(data)
if type(data.steamid) ~= "string" then
return false, "Invalid steamid"
end
if type(data.username) ~= "string" then
return false, "Invalid username"
end
if type(data.level) ~= "number" or data.level < 1 then
return false, "Invalid level"
end
return true
end
local playerData = {
steamid = "STEAM_0:1:12345",
username = "TestPlayer",
level = 1
}
local valid, error = validatePlayer(playerData)
if valid then
collection:InsertOne(playerData)
print("Player inserted")
else
print("Validation failed:", error)
end
Next Steps
- Player Systems - Complete player management
- Game Systems - Leaderboards and achievements