Skip to content
Chris Woodle edited this page Dec 21, 2022 · 1 revision

Setup

After installing the .dll into garrysmod\lua\bin, you can start using the library.

require('mongodb')
local connectionString = 'mongodb+srv://<username>:<passwod>@cluster0.123456.mongodb.net'
local client= mongodb.Client(connectionString, 'MyApplication')
local database = client:Database('myDatabase')
local myCollection= database:GetCollection('myCollection')

Creating an index

local client = mongodb.Client(connectionString, name)
local database = client:Database(dbName)

local result = database:WriteCommandWithOpts(
        {
            indexes = {
                {
                    key = { myKeyName = 1 },
                    name = "myKeyName_v0",
                    unique = true
                }
            },
            createIndexes = "my-collection-name"
        },
        {}
    )

PrintTable(result)

UpdateOne with upsert

local data = ...
local selector =  {
    myKey = "1234"
}

local update = {
    ["$set"] = {
        createdAt = os.date("!%Y-%m-%dT%TZ" , os.time())
    },
    ["$setOnInsert"] = {
        myKey = data.myKey,
        myOtherKey = data.myOtherKey
    }
}
local opts = {
    upsert = true
}

myCollection:UpdateOne(selector, update, opts)
Clone this wiki locally