Connection

Basic Connection

Create simple MongoDB connections

Basic Connection

Learn how to create basic MongoDB connections with gmsv_mongo.

Simple Connection

The simplest way to connect to MongoDB:

require("mongo")

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

if client then
    print("✓ Connected to MongoDB!")
else
    print("✗ Connection failed!")
end

Connection String Formats

Local MongoDB (No Authentication)

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

-- Custom port
local client = MongoDB.Client("mongodb://localhost:27018")

-- Using IP address
local client = MongoDB.Client("mongodb://127.0.0.1:27017")

With Authentication

-- Basic authentication
local client = MongoDB.Client("mongodb://username:password@localhost:27017")

-- With specific auth database
local client = MongoDB.Client("mongodb://admin:secretpass@localhost:27017/admin")

-- URL-encoded special characters in password
-- If password is "p@ss:word", encode as "p%40ss%3Aword"
local client = MongoDB.Client("mongodb://user:p%40ss%3Aword@localhost:27017")

Remote Servers

-- Remote server
local client = MongoDB.Client("mongodb://user:pass@192.168.1.100:27017")

-- With hostname
local client = MongoDB.Client("mongodb://user:pass@mongo.example.com:27017")

MongoDB Atlas (Cloud)

-- MongoDB Atlas uses SRV records
local client = MongoDB.Client("mongodb+srv://user:pass@cluster0.xxxxx.mongodb.net")

-- With database name
local client = MongoDB.Client("mongodb+srv://user:pass@cluster0.xxxxx.mongodb.net/mydb")

Replica Sets

-- Multiple hosts
local client = MongoDB.Client("mongodb://host1:27017,host2:27017,host3:27017")

-- With replica set name
local client = MongoDB.Client("mongodb://host1:27017,host2:27017/?replicaSet=myReplicaSet")

Connection Verification

Always verify your connection before performing operations:

require("mongo")

local function connectToMongo(connectionString)
    local client = MongoDB.Client(connectionString)

    if not client then
        print("ERROR: Failed to connect to MongoDB")
        print("Check that:")
        print("  - MongoDB server is running")
        print("  - Connection string is correct")
        print("  - Network allows the connection")
        return nil
    end

    -- Test by listing databases
    local databases = client:ListDatabases()
    if databases then
        print("✓ Connection verified!")
        print("  Found", #databases, "database(s)")
        return client
    else
        print("✗ Connection test failed")
        return nil
    end
end

-- Usage
local client = connectToMongo("mongodb://localhost:27017")
if client then
    -- Proceed with operations
end

Connection Patterns

Singleton Pattern

For most Garry's Mod addons, use a single connection:

-- In your addon's initialization
local MongoClient = nil

local function GetMongoClient()
    if not MongoClient then
        MongoClient = MongoDB.Client("mongodb://localhost:27017")
    end
    return MongoClient
end

-- Usage anywhere in your addon
local client = GetMongoClient()
local db = client:Database("mydb")

Module Pattern

-- mongo_connection.lua
local M = {}

M.client = nil
M.db = nil

function M.Initialize(connectionString, dbName)
    M.client = MongoDB.Client(connectionString)
    if M.client then
        M.db = M.client:Database(dbName)
        return true
    end
    return false
end

function M.GetDatabase()
    return M.db
end

function M.GetCollection(name)
    if M.db then
        return M.db:Collection(name)
    end
    return nil
end

return M

Error Scenarios

MongoDB Not Running

local client = MongoDB.Client("mongodb://localhost:27017")
-- Returns nil if MongoDB server is not running
-- Check server console for error details

Invalid Connection String

-- Missing protocol - INVALID
local client = MongoDB.Client("localhost:27017")  -- nil

-- Correct format
local client = MongoDB.Client("mongodb://localhost:27017")  -- works

Authentication Failure

-- Wrong credentials
local client = MongoDB.Client("mongodb://wrong:credentials@localhost:27017")
-- Returns nil, check console for auth error

Next Steps