Mongo
Important Note
The Mongo module has most, but not all, functionality of the full client. It is recommended that you manage your databases using an external tool. See Administration below.
Client-Side Data
For simple data manipulation using Mongo, take a look at the Data module.
core.mongo
Connect to a database and return a database object. If the database does not exist, it will be created.
core.mongo( db_name )
Parameters
Name | Description | Type | Required |
---|---|---|---|
db_name | The database to connect to. | String | Y |
Example
local db, err = core.mongo( "app" )
use
Change the current working database. If the database does not exist, it will be created.
db:use( db_name )
Parameters
Name | Description | Type | Required |
---|---|---|---|
db_name | The database to connect to. | String | Y |
Example
local db = db:use( "app2" )
close
Close the database connection.
db:close()
Close Connections
To keep memory usage down, you should always close the database connection when finished.
collection
Select and return a collection to operate on. If the collection does not exist, it will be created.
db:collection( name )
Parameters
Name | Description | Type | Required |
---|---|---|---|
name | The collection name to use. | String | Y |
Example
local coll = db:collection( "users" )
listCollections
Retreive a list of collections. Returns a table array, or nil and an error.
db:listCollections()
Parameters
This method has no parameters.
Example
local list, err = db:listCollections() for i=1, #list do print(list[i]) -- collection name end
Collections
The following methods operate on collections. See db:collection above to gain access to a collection object.
save
Inserts or updates a single document. If no id field is present, creates a new document, otherwise updates the document. Returns the document id, or nil and an error.
collection:save(doc)
Parameters
Name | Description | Type | Required |
---|---|---|---|
doc | A data table with the document data. | Table | Y |
Example
Insert a new document
local doc = { name = "Jimmy", age = 20, active = true, colors = { "red", "green", "blue" } } local id, err = coll:save(doc)
Update an existing document
local doc = coll:findOne(<queryOrId>) doc.name = "Nancy" local id, err = coll:save(doc)
Note
This method is the same as setting upsert=true when using the update method.
insert
Insert multiple documents into a collection. Returns array of ids and number inserted, or nil and an error.
collection:insert( docs )
Parameters
Name | Description | Type | Required |
---|---|---|---|
docs | A table array of data tables with the document data. | Table | Y |
Example
local docs = { { name = "Tina", age = 24 }, { name = "Jeff", age = 36 } } local ids, errOrNum = coll:insert( docs )
findOne
Find and return the first document that matches the query or id. Returns the doc, or nil and an error.
collection:findOne(queryOrId, fields)
Parameters
Name | Description | Type | Required |
---|---|---|---|
queryOrId | A table based query, or a string based id. | Table or String | Y |
fields | Limit the fields returned from the document. Returns all fields by default. | Table | N |
Example
By query
local doc, err = coll:findOne( {name="Jeff", age=36} )
By id
local doc, err = coll:findOne( "59a583516362392a28000001" )
Limit fields
-- return only the 'name' field local doc, err = coll:findOne( {name="Jeff", age=36}, {name=true} ) -- return all except the 'name' field local doc, err = coll:findOne( {name="Jeff", age=36}, {name=false} )
See also
find
Find multiple documents based on query. Returns a new cursor object.
collection:find(query, fields)
Parameters
Name | Description | Type | Required |
---|---|---|---|
queryOrId | A table based query, or a string based id. | Table or String | Y |
fields | Limit the fields returned from the document. Returns all fields by default. | Table | N |
Example
-- find documents where name equals "Jimmy" local cursor = coll:find({ name = "Jimmy" }) -- find documents where age greater than 20 local cursor = coll:find({ age = {["$gt"] = 20} }) -- find documents where age greater than 20, and name is "Tina" local cursor = coll:find({ age = {["$gt"] = 20}, name = "Tina" })
Chainable Cursors
This method returns a cursor object which is chainable. For example, to return all documents found by the query in one call: local docs = coll:find( query ):all()
See also
findAndModify
Finds the first document that matches the query and updates it in place based on the options. Returns old doc (unless new option is set), or nil, and an error.
collection:findAndModify(queryOrId, options)
Parameters
Name | Description | Type | Required |
---|---|---|---|
queryOrId | A table based query, or a string based id. | Table or String | Y |
options | Options for the modification (see below). | Table | Y |
Options Keys
Name | Description | Type | Required |
---|---|---|---|
update | Description | Table | Y |
new | Description | Bool | N |
sort | Description | Table | N |
fields | Description | Table | N |
local doc, err = col:findAndModify(query_or_id, opts)
update
Update a record. Returns number updated, or nil and an error.
collection:update(queryOrId, updateDoc, flags)
Parameters
Name | Description | Type | Required |
---|---|---|---|
queryOrId | A table based query, or a string based id. | Table or String | Y |
updateDoc | Options for the modification (see examples). | Table | Y |
flags | Flags for the update (see below). | Table | Y |
Flags Keys
Name | Description | Type | Required |
---|---|---|---|
upsert | Description | Bool | Required |
multi | Description | Bool | Required |
Example
Replace entire document
local num, err = collection:update({name="Jim"}, { name="John", age=45 })
Update and add fields
local num, err = collection:update({name="John", age=45}, { ["$set"] = { age = 43, active = true } })
Using id
local num, err = collection:update("59a583516362392a28000001", { ["$set"] = { active = false } })
Update multiple
local num, err = collection:update({active = false}, { ["$set"] = { active = true } }, { multi = true } )
Add field to documents if missing
local num, err = collection:update({ active = {["$exists"] = false }}, { ["$set"] = { active = true } }, { multi = true } )
See also
remove
Remove a document or documents based on the query. Returns number of records removed, or nil and an error.
collection:remove(queryOrId, isSingle)
Parameters
Name | Description | Type | Required |
---|---|---|---|
queryOrId | A table based query, or a string based id. | Table or String | Y |
isSingle | Remove only the first returned document when the query matches multiple documents. | Bool | N |
local num, err = coll:remove(query_id, is_single)
drop
Remove a collection and all the containing documents. Returns true, or nil and an error.
collection:drop()
Parameters
This method has no parameters.
Example
local res, err = coll:drop()
rename
Rename a collection. Returns newly named collection, or nil and an error.
collection:rename(new_name, drop)
Parameters
Name | Description | Type | Required |
---|---|---|---|
new_name | The preferred name for the collection. | String | Y |
drop | Clear all documents before renaming. Default: false | Bool | N |
Example
local new_col, err = col:rename(new_name, drop)
Moving to another database
To rename and move the collection to another database, pass the full namespace to the new_name parameter:
-- namespace <db>.<collection> col:rename("otherdb.newname")
getIndexes
The current collection indexes. Returns a table array with index objects, or nil and an error.
collection:getIndexes()
Parameters
This method has no parameters.
Index Object Keys
Name | Description | Type |
---|---|---|
key | The index key info. | Table |
name | The index name. | String |
Example
local indexes, err = coll:getIndexes() for i=1, #indexes do local index = indexes[i] --index key info for field, opt in pairs(index.key) do print(field, opt) end --index name print(index.name) end
createIndex
Create index(es) for a collection. Returns true, or nil and an error.
collection:createIndex(index_arr)
Parameters
Name | Description | Type | Required |
---|---|---|---|
index_arr | A table array of index objects. | Table | Y |
Example
Simple index
local res, err = coll:createIndex({ { key = { age = 1 } } })
Compound index
local res, err = coll:createIndex({ { key = { age = 1, name = -1 } } })
Create multiple indexes
local res, err = coll:createIndex({ { key = { name = 1 } }, { key = { age = -1, score = 1 } } })
Index names
By default Mongo will generate the index name based on the fields passed. To set an index name manually, pass a name key in the object.
local res, err = coll:createIndex({ { key = { age = 1 }, name = "age_asc" } })
dropIndex
Drop indexes for a collection. Returns true, or nil and an error.
collection:dropIndex( name )
Parameters
Name | Description | Type | Required |
---|---|---|---|
index_name | The index name to drop. | String | Y |
Example
local res, err = coll:dropIndex( "age_asc" )
See also
aggregate
Performs aggregation operation based on the pipeline commands. By default returns a cursor, or nil and an error.
collection:aggregate(pipeline)
Parameters
Name | Description | Type | Required |
---|---|---|---|
pipeline | The aggregation pipeline commands. | Table | Y |
Example
local cur, err = users:aggregate({ { ["$project"] = { name = { ["$toUpper"] = "$name" }, _id = 0 } }, { ["$sort"] = { name = 1 } } })
Output aggregation results to a collection instead of a cursor
Important
The $out key must be the last step in the pipeline. Creates and returns a new collection.
local coll, err = users:aggregate({ { ["$project"] = { name = { ["$toUpper"] = "$name" }, _id = 0 } }, { ["$sort"] = { name = 1 } }, { ["$out"] = "uppernames" } })
See also
Cursor
A cursor object contains a group of documents returned from the find method. After setting the needed cursor methods, use the all or next cursor method to retrieve the documents. For example, using all:
-- return first 10 docs from the find request local docs = cursor:limit(10):all()
Tip
Cursor object methods are chainable.
all
Return document(s) based on the previous cursor options. Returns a table array of documents, or nil and an error.
cursor:all()
Important
Always call this method last (or in a chain), to retrieve the documents from the cursor.
Parameters
This method has no parameters.
Example
local docs, err = cur:all()
sort
Sort the documents currently held in the cursor based on the sorting table. Returns the cursor.
cursor:sort( sort_tbl )
Parameters
Name | Description | Type | Required |
---|---|---|---|
sort_tbl | A table with field based sorting options. | Table | Y |
Example
--sort by age, ascending local cur = cur:sort({ age = core.ASC }) --sort by age descending and name ascending local cur = cur:sort({age = core.DESC, name = core.ASC })
skip
Skip a specific amount of documents in the cursor results. Returns the cursor.
cursor:skip(num)
Parameters
Name | Description | Type | Required |
---|---|---|---|
num | The amount of records to skip. | Number | Y |
Example
--skip the first 20 documents local cur = cur:skip( 20 )
limit
Limit the amount of documents returned based on the current cursor options. Returns the cursor.
cursor:limit(num)
Parameters
Name | Description | Type | Required |
---|---|---|---|
num | The records limit amount. | Number | Y |
Example
--return the first 10 documents local cur = cur:limit( 10 )
count
Return the current document amount based on the current cursor options. Returns a number.
cursor:count()
Parameters
This method has no parameters.
Example
local cnt = cur:count()
rewind
Set the cursor pointer back to the begining of the document results. Returns the cursor.
cursor:rewind()
Parameters
This method has no parameters.
Example
local cur = cur:rewind()
next
Interate over the cursor results. On each call, returns a document, or nil and an error.
cursor:next()
Parameters
This method has no parameters.
Example
while true do local doc = cur:next() if doc == nil then break end end
See also
distinct
Pull distinct key values from the cursor results. Returns a table array, or nil and an error.
cursor:distinct(key)
Parameters
Name | Description | Type | Required |
---|---|---|---|
key | The field key to operate on. | String | Y |
Example
local res, err = cur:distinct( "age" ) -- 'res' is a table array
MongoDB to Lua
MongoDB used JSON objects. When viewing the documentation on the MongoDB website, you must convert the JSON information to Lua. What follows are some tips to do that.
Operators
MongoDB uses special operators that are prefixed with a dollar sign ( $ ). These operators keys must be set using an array style syntax when providing them using Lua.
MongoDB Key | Lua Key |
---|---|
$inc | ["$inc"] |
$set | ["$set"] |
Example
coll:update({name="Jimmy"}, { ["$set"] = { age = 23 } })
Arrays
Arrays are rendered as indexed tables.
MongoDB Array | Lua Array |
---|---|
["red", 23, true] | {"red", 23, true} |
Example
coll:insert({ name = "Tina", colors = {"red","green","blue"} })
Append values
Append a single value
coll:update(<queryOrId>, { ["$push"] = { colors = "yellow" } })
Append multiple values
coll:update(<queryOrId>, { ["$push"] = { colors = { ["$each"] = { "brown", "purple" } } } })
Remove values
Remove first element
coll:update(<queryOrId>, { ["$pop"] = { colors = -1 } })
Remove last element
coll:update(<queryOrId>, { ["$pop"] = { colors = 1 } })
Resources
- Find Examples
- Query Operators
- Update Operators
- Array Update Operators
- Aggregation Operators
- SQL to MongoDB Mapping Chart
Administration
You can and should manage your Mongo databases using a standalone tool. Below are some free resources for managing Mongo databases.
Screencast Available
Learn more about database administration in a screencast format by Clicking here.
To connect to the Mongo database, use the host address of the server, and the password that was set when installing Coronium Core.
Remote Access
By default, a fresh Coronium Core installation allows remote access to the Mongo database with a password so that you can use client side tools to edit your databases.
While this is convenient to the developer, it is not particularly the most secure way to run the database. Instead you should only activate remote access while you work on the database, and then deactivate it when you are done.
DigitalOcean
To activate/deactivate remote MongoDB access use the mongo-remote tool by logging in with the coronium user and entering one of the following on the command line:
Activate remote access
sudo mongo-remote on
Deactivate remote access
sudo mongo-remote off
If you are having issues connecting with your MongoDB client, make sure that you have remote access in an active state.
Amazon EC2
Disable/enable port 27017 as needed in your instance security group. For more information on editing your security group click here.
Password Update
To change your Mongo password log in your Coronium Core server and run:
sudo mongo-updatepw
Disabling MongoDB
If you don't plan on using any of the Mongo based modules, like core.data or core.mongo you can reclaim some memory and resources for your system.
To disable MongoDB, you will need to log in as the root user (ubuntu on EC2) and run the following on the command line:
sudo mongo-enabled false
This will stop the MongoDB service from running. The server will automatically reboot after issuing this command.
In the future, if you decide you need MongoDB, log in as the root user (ubuntu on EC2), and run:
sudo mongo-enabled true