MongoDB

Your Coronium instance includes the MongoDB "document" database that can be accessed with the cloud api.

cloud.mongo


Limitations

Due to the way Lua handles arrays, there are some commands that are not possible to issue to Mongo. You may be able to use the :js method to run Javascript against the Mongo database to handle those cases that the Lua driver can't.


New

.new

The Mongo module works as a factory. You create a new instance like so:

--creating a mongo instance
local mongo = cloud.mongo.new()

Databases

:databases

Returns a table array of Mongo databases.

Example

local mongo = cloud.mongo.new()

local dbs, e = mongo:databases()
if not dbs then
  return cloud.error( e )
end

return dbs

Close

:close

Closes the Mongo connection.

Example

local info, e = mongo:close()

Did You Know?

Calling this method will close the connection immediately. Use it when you are done!


SetTimeout

:set_timeout

Change default timeout in milliseconds.

mongo:set_timeout( milliseconds )

Example

-- Set the timeout to 45 seconds
local r, e = mongo:set_timeout( 45000 )

GetTimeout

:get_timeout

Returns the current timeout in milliseconds.

Example

local timeout_ms, e = mongo:get_timeout()

SetKeepalive

:set_keepalive

Change the default connection keep alive in milliseconds.

mongo:set_keepalive( milliseconds )

Example

-- Set keep alive to 25 seconds
local r, e = mongo:set_keepalive( 25000 )

GetKeepaliveMS

:get_keepalive_ms

Returns the current keep alive in milliseconds.

Example

local keep_alive_ms, e = mongo:get_keepalive_ms()

UseDB

:use_db

Select the working Mongo database. See more below in Selecting a Database.

mongo:use_db( database_name )

Returns

A Mongo database Object.


Selecting a Database

Once you have your mongo instance, you will need to select the database you want to work with:

local db = mongo:use_db( 'members' )

Did You Know?

If the database does not exist, it will be created automatically.


Collections (db Object)

Every database is built of collections, you can access them from the db object.

db:collections()

Example

Retrieves an array of collections in the current db. System collections are stripped from the return.

mongo = cloud.mongo.new()
local db = mongo:use_db( 'members' )

local list,err = db:collections()
if not list then 
    return nil,err 
end

for i=1,#list do
 cloud.log(list[i])
end

db.< COLLECTION_NAME >:< METHOD >( < PARAMETERS > )

Example

To insert a document in a user collection, in the members database, you could do like so:

local mongo = cloud.mongo.new()
local db = mongo:use_db( 'members' )

db.user:insert( { name = "CoolUser" } )

Did You Know?

If a collection does not exist, it will be created automatically.


Query Filters

Field Display Filters

Some collection methods can take a field display table. This will turn on or off which fields are returned in the collection. To create a filter table for the fields do the following:

  • Create an empty table. This will be a keyed table.
  • Name the table keys as the fields you want to hide or show.
  • Use a value of 1 to show the field in the results, or 0 to hide it.

Example

local q = { userid = 123 }

-- Only the `name` field will be returned.
local result, error = db.user:find_one( q, { name = 1 } )

-- Only the `name` and `age` field will be returned.
local result, error = db.user:find_one( q, { name = 1, age = 1 } )

-- All except the `dob` field will be returned.
local result, error = db.user:find_one( q, { dob = 0 } )

Heads Up!

You can not mix filter flags. It's either show flags, or hide.

Sorting Filters

Sorting filters work similar to field filters, and can be created like so:

  • Create an empty table. This will be a keyed table.
  • Name the table keys as the fields you want to sort on.
  • Use a value of cloud.mongo.ASC to sort ascending, or cloud.mongo.DESC for descending.

Example

local q = { org = 'customer_support' }

-- Sort on the `name` field, descending.
local c, e = db.user:find( q, nil, { name = cloud.mongo.DESC } )

-- Sort on `name` ascending and `age` descending.
local c, e = db.user:find( q, nil, { name = cloud.mongo.ASC, age = cloud.mongo.DESC } )

-- Sort by name, then age. Ascending.
local c, e = db.user:find( q, nil, { name = cloud.mongo.ASC, age = cloud.mongo.ASC } )

Note: You can also use 1 and -1 for ascending order and descending order, respectively.


Collection Methods

The following methods can be used on collections.


Count

:count

Returns a collection document count based on query.

db.<collection>:count( query )

Example

local count = db.user:count( { access=true } )

Pager

:pager

db.<collection>:pager( query[, page][, per_page][, fld_filter][, sort_filter] )

Parameters

Key Description Type Default Required
query A JSON-able Lua query table. table nil Y
page The page number. Starts from 1. number 1 N
per_page Amount of results per page. number 10 N
fld_filter A table with field flags (See above). table nil N
sort_filter A table with sorting flags (See above). table nil N

Returns

The results will hold the documents in a table array, if any.

Example

local mongo = cloud.mongo.new()
local db = mongo:use_db( 'members' )

local results, e = db.user:pager( { ['$gt'] = { age = 36 } }, 2, 10 )

Insert

:insert

Insert a document into the collection.

db.<collection>:insert( document )

Parameters

Key Description Type Default Required
document A document table to insert. table nil Y

Example

local mongo = cloud.mongo.new()
local db = mongo:use_db( 'members' )

local r, e = db.user:insert( { name = "Steve", age = 40 } )

InsertMany

:insert_many

Insert multiple documents into the collection.

db.<collection>:insert_many( documents[, cont_on_err] )

Parameters

Key Description Type Default Required
documents A table array of documents to insert. table nil Y
cont_on_err Continue inserting records even if one errors. boolean false N

Example

local mongo = cloud.mongo.new()
local db = mongo:use_db( 'members' )

local docs =
{
  { name = "Bill", age = 30 },
  { name = "Opus", age = 34 }
}

local r, e = db.user:insert_many( docs )

Update

:update

db.<collection>:update(query, update[, upsert][, multi][, replace])

Parameters

Key Description Type Default Required
query The table query for the update doc. table nil Y
update The update data table. table nil Y
upsert Create a document, if needed. boolean false N
multi_update Update all matching records. boolean false N
replace Disable in-place updates. boolean false N

Heads Up!

By default, updates are performed as a $set. Enable replace if you want to use MongoDB operators such as $unset, or if you want update to replace the entire document.

Returns

A result, or nil and error.

Example

local mongo = cloud.mongo.new()
local db = mongo:use_db( 'leaderboard' )

--update score to 300 for player 'Sally'
local r, e = db.scores:update( { player="Sally" }, { score = 300 } )
if not r then
  return cloud.error( e )
end

return r

UpdateMany

:update_many

db.<collection>:update_many( batch_query_table )

Parameters

Key Description Type Default Required
batch_query_table A table array of update documents (See example). table nil Y

Returns

A result, or nil and error.

Example

local mongo = cloud.mongo.new()
local db = mongo:use_db( 'leaderboard' )

--== q=query | u=update
local batch =
{
  { q={name="Chris"}, u={name="Jim"}, upsert=[Boolean], multi=[Boolean] },
  { q={ age={["$gt"] = 30} }, u={selected=true}, upsert=[Boolean], multi=[Boolean] }
}

local result, e = db.scores:update_many( batch )

Delete

:delete

db.<collection>:delete(delete_query[, delete_single])

Parameters

Key Description Type Default Required
delete_query A JSON-able Lua table query. table nil Y

Example

local mongo = cloud.mongo.new()
local db = mongo:use_db( 'leaderboard' )

--delete record with name 'Jim' and score of 100
local r, e = db.scores:delete( { name = 'Jim', score = 100 } )

DeleteMany

:delete_many

db.<collection>:delete_many(delete_query)

Parameters

Key Description Type Default Required
delete_query A JSON-able Lua table query. table nil Y

Example

local mongo = cloud.mongo.new()
local db = mongo:use_db( 'leaderboard' )

--delete records with score less or equal to 10
local r, e = db.scores:delete_many( { score = { ["$lte"] = 10 } } )

Find

Heads Up!

The find method will only return a single record result. For multiple records see the pager method.

:find

db.<collection>:find( query )

Parameters

Key Description Type Default Required
query A JSON-able Lua table to search against. table nil Y

Example

local mongo = cloud.mongo.new()
local db = mongo:use_db('members')

--find `user` Alice
local doc, e = db.user:find( { name = 'Alice' } )
if not doc then
  return cloud.error( e )
end

return doc

FindMany

Did You Know?

Unless you need direct access to the mongo cursor, using the pager method is easier, and better optimized, than using find_many directly.

:find_many

db.<collection>:find_many(query_table[, fld_filter,])

Parameters

Key Description Type Default Required
query_table A JSON-able Lua table to search against. table nil Y
fld_filter A Query Filter for the document fields. table nil N

Returns

A result, or nil and error.

Example

local mongo = cloud.mongo.new()
local db = mongo:use_db('leaderboard')

--find scores greater than 100
local cursor, e = db.scores:find_many( { score = { ["$gt"] = 100 } } )
if not cursor then
  return cloud.error( e )
end

return cursor:get_pairs()

Aggregate

:aggregate

See Mongo aggregation db command docs for more details.

db.<collection>:aggregate( pipeline )

Example

local result_doc, e = db.user:aggregate( pl_tbl )

Js

:js

Runs a javascript command against the Mongo database.

In Progress


Cursors Methods

Did You Know?

Using the pager method is easier, and better optimized, than using cursors directly.

When issuing a :find_many method, you will receive a cursor object. You can iterate over this object and extract results.

local cursor, e = db.user:find( { age = { ['$lt'] = 60 } } )

This object has the following methods available:

Limit

:limit

Limit the amount of documents returned from the cursor.

cursor:limit( amount )

Sort

:sort

Sort the documents in the cursor. See Query Filters for more details.

cursor:sort( sort_filter )

Skip

:skip

Skip a certain amount of documents in the cursor.

cursor:skip( amount )

Next

:next

Get the next document in the cursor.

cursor:next( amount )

GetPairs

:get_pairs

Get a table representation of the cursor.

Example

local t_pairs = cursor:get_pairs()

Constants

Ascending order: cloud.mongo.ASC

Descending order: cloud.mongo.DESC


Converting BSON ID

To be able to search against the Mongo provided identifier, you can convert the string id using:

local id = cloud.mongo.toObjectID( id_str )

Usage Example

local function grabData()
--Find one data doc that is marked "done = false"
    local res,err = db.data:find_one({done=false},{data=1})
    if err then return nil,err end

    if not res.data or not res._id then
        return nil,"Bad response"
    end

 --Save our data and record what doc it came from
    local myData = {
                    ['data']= res.data,
                    ['id'] = res._id
                    }
--Mark the doc we found as "done = true" so we don't collect it again
--String ID must be converted back to the original encoding.
    res,err = db.data:update({_id = cloud.mongo.toObjectID(myData['id'])},{done=true})
    if err then return nil,err end

    return myData,nil
end

Administration

A browser based MongoDB tool is available at https://your.coronium.instance:12000/

The default log in is:

User: cloud

Password: cloudadmin