1、下载lua-resty-mongol https://github.com/bigplum/lua-resty-mongol

2、配置_mongo.conf文件,在conf创建_mongo.conf文件,配置信息如下

#_mongo.conf
server {
listen ;
#server_name 192.168.1.128;
#关闭lua_code 缓存 location /lua {
content_by_lua_file /opt/openresty/lualib/resty/mongol/test_lua.lua;
}
location /lua_mongo {
content_by_lua_file lualib/resty/mongol/test_mongol.lua; }
location /lua_test {
set $test "hello world";
#使用acess 阶段做准入条件处理
access_by_lua '
if (ngx.var.test =="hello world") then
ngx.say("验证通过"..ngx.var.test)
else
ngx.log(ngx.ERR,"验证失败","")
end
';
#业务处理
content_by_lua '
ngx.header.content_type ="text/plain";
local a, b =;
ngx.say(ngx.var.test..a);
';
} }

然后记得把_mongo.conf配到主配置文件上,在nginx.conf里添加【include _mongo.conf; 】

3、在content_by_lua_file lualib/resty/mongol/文件夹下创建数据库的测试文件test_mongol.lua,代码如下:

local mongo =require "resty.mongol"
local json = require "cjson"
--获取连接对象
local conn =mongo:new()
conn:set_timeout()
--获取连接客户端
local ok,err =conn:connect("127.0.0.1",) if not ok then
ngx.say("connect failed"..err)
end
--获取数据库
local db = conn:new_db_handle("testdb")
--用户授权
local ok ,err = db:auth("","") if ok then
ngx.say("user auth success"..ok)
end
--获取集合
local coll = db:get_col("testtable")
--获取document集合
local cursor = coll:find({}) --json 转码
--
function json_decode( str )
local json_value =nil
pcall(function (str) json_value = json.decode(str) end, str)
return json_value
end --循环
for index,item in cursor:pairs() do
ngx.say('数据: '..index)
if not item['url'] then
ngx.say('数据:'..item["title"])
else
ngx.say('数据:'..item["title"]..item['url'])
ngx.say(json_decode(item['url']))
end end
--获取单个集合
local res =coll:find_one({key = }) if res then ngx.say(res['title'])
end --插入集合
local bson1 ={title ='哈哈',url = 'www.baidu.com',key = };
--插入table 表中
local docs ={bson1}; local rsOk,err =coll:insert(docs,,) if err then
ngx.say('error--'..err)
else
ngx.say('ok---- '..rsOk)
end --删除操作
local deOk,err = coll:delete({title ='你好'},,) if err then
ngx.say('delete error--'..err)
else
ngx.say('delete ok--'..deOk)
end --关闭连接
if conn then conn:close()
end

最新文章

  1. Hibernate 错题分析
  2. 一种更清晰的Android架构(转)
  3. IOS中延迟执行的几种方法
  4. ASM:《X86汇编语言-从实模式到保护模式》第七章应用例:用adc命令计算1到1000的累加
  5. mysql force index() 强制索引的使用
  6. 树形DP(01组合背包The Ghost Blows Light HDU4276)
  7. 第一章 C++简介
  8. 学习笔记——XSLT转换器的使用(Xalan和Saxon) .(转)
  9. 08_XML的解析_SAX解析
  10. openwrt advanced configuration
  11. LeetCode-Word LadderII
  12. 我的Android进阶之旅------>Android拍照小例子
  13. SVN学习笔记
  14. 【Python】 文件和操作文件方法
  15. 算法面试题-leetcode学习之旅(一)
  16. 解决python编码问题
  17. [Canvas]用透明PNG图在背景上画前景能不遮挡背景
  18. nodejs(五)同步异步--BLOCKING THE EVENT LOOP
  19. js如何模拟multipart/form-data类型的请求
  20. C# 分页方法

热门文章

  1. qt 使用qtxlsx 读写excel
  2. springmvc中配置RESTful风格控制器
  3. Android学习——BroadCast(二)
  4. Excel 函数使用
  5. 安装Access Database Engine后,提示未注册Microsoft.ACE.OLEDB.12.0
  6. 【Leetcode】【Medium】Linked List Cycle II
  7. openvpn(上)
  8. February 22 2017 Week 8 Wednesday
  9. MVVM的核心:双向绑定
  10. CTSC2018 && APIO2018 && SDOI2018R2游记