Lua 操作 MongoDB 数据库实例_Lua

最近有个工作是使用Nginx + Lua实现一个操作MongoDB数据库的API,主要实现其count和query功能。之前没有写过Lua,于是也就勉强着上手,在cloudwu的 lua-mongo 的基础上实现了操作MongoDB的API。

cloudwu的lua-mongo驱动实现了连接Mongo,进行find和findOne等基本操作的功能,所以在lua-mongo的基础上增加了count和query等方法。修改的具体内容如下:

1、API基于luajit-2.0开发,相当于lua 5.1,需要使用lua-compat-5.2兼容lua 5.2

2、使用ngx.socket.tcp替换mongo.socket模块

3、增加了count,query,auth等方法

修改之后的代码见: lua-mongo

具体的操作MongoDB的lua代码如下:

复制代码 代码如下:

-- lua mongo test script
-- utils
function string:split(sep)
  local sep, fields = sep or ":", {}
  local pattern = string.format("([^%s]+)", sep)
  self:gsub(pattern, function(c) fields[#fields + 1] = c end)
  return fields
end
-- 常量
HOST = "127.0.0.1"
PORT = 27017
KEEPALIVE_TIMEOUT = 60000
KEEPALIVE_SIZE = 100
CONN_TIMEOUT = 3000
DB_USER = "user"
DB_PASSWD = "password"
DB_NAME = "blog"
DB_COLLECTION = "article"
-- 引用
mongo = require("mongo")
cjson = require("cjson.safe")
cbson = require("bson")
-- 状态
local status_msg = "error"
local status_code = 500
local message = "unknown error"
local mongo_query = {["category_id"] = {["$in"] = {1,2,3,4}}, ["status"] = {["$ne"] = 2}, ["create_time"] = {["$lte"] = 1427102260}}
local mongo_sort = {["create_time"] = 1}
local mongo_limit = 100
local mongo_skip = 0
local mongo_fields = { ["_id"] = false }
-- 涉及到时间的字段,需要使用bson转化一下
if mongo_query["create_time"] then
  local create_time = mongo_query["create_time"]
  local t = type(create_time)
  if t == "table" then
    for key, value in pairs(create_time) do
      mongo_query["create_time"][key] = cbson.date(value)
    end
  else
    mongo_query["create_time"] = cbson.date(create_time)
  end
end
local conn = mongo.client({ host = HOST, port = PORT })
conn:set_timeout(CONN_TIMEOUT)
local db = conn:getDB(DB_NAME)
local reused_times = conn:get_reused_times()
if reused_times == 0 then
  db:auth(DB_USER, DB_PASSWD)
end
local col = db:getCollection(DB_COLLECTION)
local result = {}
-- count
local count, err = col:count(mongo_query)
local ok, err = conn:set_keepalive(KEEPALIVE_TIMEOUT, KEEPALIVE_SIZE)
if count ~= nil then
  result = count
  status_code = 200
  status_msg = "ok"
  message = "success"
end
-- query
local bson_obj
if mongo_sort then
  bson_obj = cbson.encode_order("$query", mongo_query, "$orderby", mongo_sort)
else
  bson_obj = cbson.encode({ ["$query"] = mongo_query })
end
local results = col:query(bson_obj, mongo_fields, mongo_skip, mongo_limit)
local ok, err = conn:set_keepalive(KEEPALIVE_TIMEOUT, KEEPALIVE_SIZE)
if results then
  for _, object in pairs(results) do
    for key, value in pairs(object) do
      if value == cbson.null then
        object[key] = cjson.null
      else
        local type_name, value = cbson.type(value)
        object[key] = value
      end
    end
  end
  result = results
  status_code = 200
  status_msg = "ok"
  message = "success"
end
-- findOne
local results = col:findOne({["id"] = 14 })
local ok, err = conn:set_keepalive(KEEPALIVE_TIMEOUT, KEEPALIVE_SIZE)
if results then
  for key, value in pairs(results) do
    if value == cbson.null then
      results[key] = cjson.null
    else
      local type_name, value = cbson.type(value)
      results[key] = value
    end
  end
  result = results
  status_code = 200
  status_msg = "ok"
  message = "success"
end
ngx.status = status_code
json_out = cjson.encode({ status = status_msg, message = message, data = result })
ngx.header["Content-Length"] = json_out:len()
ngx.print(json_out)

时间: 2024-08-03 17:17:53

Lua 操作 MongoDB 数据库实例_Lua的相关文章

Lua 操作 MongoDB 数据库实例

这篇文章主要介绍了Lua 操作 MongoDB 数据库实例,本文给出了修改后的lua-mongo API和具体的操作MongoDB 数据库代码,需要的朋友可以参考下     最近有个工作是使用Nginx + Lua实现一个操作MongoDB数据库的API,主要实现其count和query功能.之前没有写过Lua,于是也就勉强着上手,在cloudwu的 lua-mongo 的基础上实现了操作MongoDB的API. cloudwu的lua-mongo驱动实现了连接Mongo,进行find和find

yii2框架 操作 mongodb 数据库实例教程

一:安装yii2  关于安装yii2我们就不??铝耍?故抢??omposer安装下载,我们可以安装basic 模版 composer global require "fxp/composer-asset-plugin:~1.0.3" composer create-project --prefer-dist yiisoft/yii2-app-basic basic 或者是advanced composer global require "fxp/composer-asset-

PHP连接操作access数据库实例

 这篇文章主要介绍了PHP连接操作access数据库实例,本文直接给出实现代码,需要的朋友可以参考下     因为之前做的PingSwitch要做一个WEB展示的前端,因为一开始用了Delphi和access的结构,而Delphi与MySQL的连接又相对麻烦,最后只能选择用PHP+Access的组合,比较奇怪,但是也合理····· 在PHP中连接access数据库的话我们必须ADO来连接,这跟ASP中连接数据库非常的类似.下边给出了一段DEMO供大家参考. <?PHP /* 创建ADO连接 */

php使用PDO操作MySQL数据库实例

 这篇文章主要介绍了php使用PDO操作MySQL数据库,实例分析了PDO的开启与针对MySQL数据库的增删改查等基本操作方法,具有一定参考借鉴价值,需要的朋友可以参考下     本文实例讲述了php使用PDO操作MySQL数据库的方法.分享给大家供大家参考.具体分析如下: PDO是mysql数据库操作的一个公用类,我们不需要进行自定类就可以直接使用pdo来操作数据库,但是在php默认配置中pdo是未开启所以我们必须先在php.ini中开启它才可以使用,这里来详细介绍一下. PDO扩展为PHP访

不使用spring的情况下用java原生代码操作mongodb数据库的两种方式

由于更改了mongodb3.0数据库的密码,导致这几天storm组对数据进行处理的时候,一直在报mongodb数据库连接不上的异常.   主要原因实际上是和mongodb本身无关的,因为他们改的是配置文件的密码,而实际上这个密码在代码中根本就没有使用,他们在代码中已经把用户验证信息写死.   在协助他们解决这个问题的时候,我看到他们代码中在和mongodb数据库交互时使用了已经不被建议使用的方法,于是便抽时间尝试了一下另一种被建议的方式实现各功能.   当然了,生产环境中用的是mongodb集群

node.js操作mongoDB数据库示例分享_node.js

连接数据库 复制代码 代码如下:  var mongo=require("mongodb");  var host="localhost";  var port=mongo.Connection.DEFAULT_PORT;  var server=new mongo.Server(host,port,{auto_reconnect:true});//创建数据库所在的服务器服务器  var db=new mongo.Db("node-mongo-exampl

php操作MongoDB类实例

 本文实例讲述了php操作MongoDB类的方法.分享给大家供大家参考.具体如下: 1. MyMongo.php文件: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

php操作MongoDB类实例_php技巧

本文实例讲述了php操作MongoDB类的方法.分享给大家供大家参考.具体如下: 1. MyMongo.php文件: <?php /** * 仿写CI的MongoDB * @author sparkHuang 2011-11-03 * */ class MyMongo { private $mongo_config = "mongo_config.php"; private $connection; private $db; private $mongo_connect_stri

【MongoDB for Java】Java操作MongoDB数据库_MongoDB

本篇文章主要介绍Java操作MongoDB. 开发环境: System:Windows IDE:eclipse.MyEclipse 8 Database:mongoDB 开发依赖库: JavaEE5.mongo-2.5.3.jar.junit-4.8.2.jar   一.准备工作 1. 首先,下载mongoDB对Java支持的驱动包 驱动包下载地址:http://www.jb51.net/softs/41751.html mongoDB对Java的相关支持.技术:http://www.mongo