Connection

Database Operations

Working with MongoDB databases

Database Operations

Learn how to work with MongoDB databases using gmsv_mongo.

Getting a Database

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

MongoDB creates databases automatically when you first write data to them.

Listing Databases

List all databases on the MongoDB server:

local databases = client:ListDatabases()

if databases then
    print("Available databases:")
    for i, dbName in ipairs(databases) do
        print(string.format("  %d. %s", i, dbName))
    end
else
    print("Failed to list databases")
end

Output:

Available databases:
  1. admin
  2. config
  3. local
  4. gameserver

Collection Operations

Getting a Collection

local players = db:Collection("players")

Listing Collections

List all collections in a database:

local collections = db:ListCollections()

if collections then
    print("Collections in database:")
    for i, colName in ipairs(collections) do
        print(string.format("  %d. %s", i, colName))
    end
end

Creating a Collection

Explicitly create a collection:

local success = db:CreateCollection("new_collection")

if success then
    print("✓ Collection created")
else
    print("✗ Failed to create collection")
end

Collections are also created automatically when you first insert data.

Dropping a Collection

Remove a collection and all its data:

local success = db:DropCollection("old_collection")

if success then
    print("✓ Collection dropped")
else
    print("✗ Failed to drop collection")
end

Dropping a collection permanently deletes all documents in it. This cannot be undone!

Database Statistics

Get statistics for a collection:

local stats = db:Stats("players")

if stats then
    print("Collection Statistics:")
    print("  Count:", stats.count)
    print("  Size:", stats.size, "bytes")
    print("  Storage Size:", stats.storageSize, "bytes")
    print("  Avg Object Size:", stats.avgObjSize, "bytes")
end

Dropping a Database

Remove an entire database:

local success = db:Drop()

if success then
    print("✓ Database dropped")
end

WARNING: This permanently deletes the entire database and all its collections. Use with extreme caution!

Complete Example

require("mongo")

-- Connect
local client = MongoDB.Client("mongodb://localhost:27017")
if not client then return end

-- List existing databases
print("=== Existing Databases ===")
for _, name in ipairs(client:ListDatabases()) do
    print("  " .. name)
end

-- Get/create database
local db = client:Database("my_game")

-- Create collections
db:CreateCollection("players")
db:CreateCollection("items")
db:CreateCollection("logs")

-- List collections
print("\n=== Collections ===")
for _, name in ipairs(db:ListCollections()) do
    print("  " .. name)
end

-- Get collection statistics
local players = db:Collection("players")
players:InsertOne({ name = "test" })  -- Add some data

local stats = db:Stats("players")
if stats then
    print("\n=== Player Stats ===")
    print("  Documents:", stats.count)
end

-- Cleanup
db:DropCollection("logs")  -- Remove unused collection

Database Method Reference

MethodDescriptionReturns
client:Database(name)Get database referenceMongoDBDatabase
client:ListDatabases()List all databasestable or nil
db:Collection(name)Get collection referenceMongoDBCollection
db:ListCollections()List all collectionstable or nil
db:CreateCollection(name)Create new collectionboolean
db:DropCollection(name)Delete a collectionboolean
db:Stats(collection)Get collection statisticstable or nil
db:Drop()Delete entire databaseboolean

Best Practices

  1. Use meaningful names: Choose clear database and collection names
  2. Separate concerns: Use different collections for different data types
  3. Don't drop in production: Be extremely careful with Drop operations
  4. Check return values: Always verify operations succeeded

Next Steps