lua mongodb quickstart

1.1k 词
    <p>Here is the tutorial to write and build Lua application that can communicate with MongoDB database.</p>

Dependency Installation

At first, we need to install LuaRocks. Here is the tutorial.

We need to install dependency to access MongoDB database through Lua. Execute the command to install dependency:

1
luarocks install lua-mongo


Dependency Document

Here is the link of document and its Github.

Sample Code

Below is the sample code to do MongoDB query. The file name is mongoDB.lua:

1
2
3
4
5
6
7
8
9
10
11
12
local mongo = require('mongo')

local client = mongo.Client 'mongodb://host_ip:port'
local database = client:getDatabase('database_name')
local collection = database:getCollection('table_name')

local query = mongo.BSON '{ "id" : { "$gt" : "0" } }'

for document in collection:find(query):iterator()
do
print(document.id, document.name)
end

Then execute above lua script using following command:

1
lua mongoDB.lua

</div>

<footer>
    <div class="alignright">
      
      <a href="javascript:void(0)" class="share-link bdsharebuttonbox" data-cmd="more">Share</a>
    </div>
    
    



    
  <div class="clearfix"></div>
</footer>