Examples

Examples

Real-world examples and use cases for gmsv_mongo

Examples

This section contains practical examples demonstrating gmsv_mongo in real-world scenarios.

Categories

Basic Examples

Connection and simple CRUD operations

Player Systems

Player data, inventories, and progression

Game Systems

Leaderboards, achievements, and matchmaking

Server Administration

Bans, logs, and monitoring

Quick Examples

Save Player Data

function SavePlayer(ply)
    local players = db:Collection("players")

    players:UpdateOneAsync(
        { steamid = ply:SteamID() },
        {
            ["$set"] = {
                username = ply:Nick(),
                credits = ply.credits,
                level = ply.level,
                last_seen = os.time()
            }
        },
        function(err) 
            if err then print("Save error:", err) end
        end
    )
end

Load Player Data

function LoadPlayer(ply, callback)
    local players = db:Collection("players")

    players:FindOneAsync(
        { steamid = ply:SteamID() },
        function(err, data)
            if data then
                ply.credits = data.credits
                ply.level = data.level
            else
                -- New player defaults
                ply.credits = 1000
                ply.level = 1
            end
            if callback then callback() end
        end
    )
end

Get Leaderboard

function GetLeaderboard(callback)
    local players = db:Collection("players")

    players:AggregateAsync({
        { ["$match"] = { banned = { ["$ne"] = true } } },
        { ["$sort"] = { score = -1 } },
        { ["$limit"] = 10 },
        { ["$project"] = { username = 1, score = 1, _id = 0 } }
    }, function(err, results)
        callback(results or {})
    end)
end