Skip to content
develephant edited this page Feb 4, 2016 · 1 revision

Requring the module will return a function that creates a Mongo object when called:

local mongol = require "resty-mongol"
local mongo = mongol() -- return a connection object

Methods:

Connection

:connect

Connect to a Mongo instance.

Parameters

Name Description Default Required
host The Mongo host address "localhost" No
port The Mongo port number 27017 No

Returns

On success returns 1, or nil and error message.

local ok, err = mongo:connect( host, port )

:databases

Get available databases from this Mongo instance.

Parameters

None

Returns

A Lua table array describing databases on the server.

Namespace Type
databases.name String
databases.empty Boolean
databases.sizeOnDisk Number
local dbs = mongo:databases()
for _, db in ipairs( dbs ) do
  ngx.say( db.name )
end

:set_db_handle

Select a Mongo database to use.

Parameters

Name Description Default Required
database_str The name of a database none Yes

Returns

Mongo database object, or nil.

local db = mongo:new_db_handle( database_str )

:close

Close the connection to the Mongo instance.

Parameters

None

Returns

On success returns 1, or nil and error message.

local ok, err = mongo:close()

:set_timeout

Sets socket connecting, reading, writing timeout value, unit is milliseconds.

Parameters

Name Description Default Required
timeout_ms The socket timeout in milliseconds 30000 No

Returns

On success returns 1, or nil and error message.

local ok, err = mongo:set_timeout( timeout_ms )

:set_keepalive

Keeps the socket alive for msec by ngx_lua cosocket.

Parameters

Name Description Default Required
msec The socket keep-alive in milliseconds 30000 No
pool_size The size of the keep-alive socket pool ? No

Returns

On success returns 1, or nil and error message.

local ok, err = mongo:set_keepalive( msec, pool_size )

:get_reused_times

Returns the how many times this socket has been reused (see set_keepalive).

Parameters

None

Returns

On success returns times reused, or nil and error message.

local times_reused, err = mongo:get_reused_times()

:ismaster

Returns a boolean indicating if this is the master server and a table of other hosts this server is replicating with.

Parameters

None

Returns

On success returns Boolean and a table of hosts, or nil and error message.

local is_master, hostsOrErr = mongo:get_reused_times()

:getprimary

Returns a new connection object that is connected to the primary server.

Parameters

Name Description Default Required
already_checked Boolean (usage unknown) ? No

Returns

On success returns connection object, or nil and error message.

local new_conn, err = mongo:getprimary()

:shutdown

Shuts down the Mongo database server.

You probably don't want to use this. See :close() instead.

Parameters

None

Returns

Nothing

mongo:shutdown()
Clone this wiki locally