How to Use lua-mongo library in Lua Programming?

Lua provides different libraries that can be used to work with MongoDB. The most popular framework that enables us to work with MongoDB in Lua is lua-mongo.

Lua-mongo is a binding to MongoDB C Driver for Lua −

  • It provides a Unified API for MongoDB commands, CRUD operations and GridFS in MongoDB C Driver.
  • Transparent conversion from Lua/JSON to BSON for convenience.
  • Automatic conversion of Lua numbers to/from BSON Int32, Int64 and Double types depending on their capacity without precision loss (when Lua allows it). Manual conversion is also available.

You can download MongoDB with the help of this command −

luarocks install lua-mongo

MongoDB Setup

In order to use the following examples to work as expected, we need the initial db setup. The assumptions are listed below.

  • You have installed and set up MongoDB and the /data/db folder to store the databases.
  • You have created a database named lua-mongo-test and a collection named test.

Importing MongoDB

We can use a simple require statement to import the MongoDB library assuming that your Lua implementation was done correctly.

local mongo = require 'mongo'

The variable mongo will provide access to the functions by referring to the main MongoDB collection.

Now that we have the setup completed, let's write an example where we will see how we can make use of the different MongoDB queries inside Lua using the lua-mongo framework.


Consider the example shown below −

local mongo = require 'mongo'
local client = mongo.Client('mongodb://')
local collection = client:getCollection('lua-mongo-test', 'test')
-- Common variables
local id = mongo.ObjectID()
collection:insert{_id = id, name = 'John Smith', age = 50}
collection:insert{_id = id, name = 'Mukul Latiyan', age = 24}
collection:insert{_id = id, name = 'Rahul', age = 32}
for person in collection:find({}, {sort = {age = -1}}):iterator() do
   print(, person.age)

In the above example, we are trying to sort the image of the different entries that are present inside our mongoDB collections in a descending order.


John Smith 50
Rahul 32
Mukul Laityan 24