Skip to content

Instantly share code, notes, and snippets.

@narate
Created August 11, 2016 10:09
Show Gist options
  • Save narate/5ae51adff6a0ba2b7ef298aa8d64dd20 to your computer and use it in GitHub Desktop.
Save narate/5ae51adff6a0ba2b7ef298aa8d64dd20 to your computer and use it in GitHub Desktop.
OpenResty (ngx_lua) MongoDB ISODate()
local mongol = require "resty.mongol"
local bson = require "resty.mongol.bson"
local conn = mongol:new()
conn:set_timeout(1000)
local ok, err = conn:connect('127.0.0.1', '27017')
if not ok then
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.say('Failed : '.. err)
ngx.exit(ngx.status)
end
local ngx_now = ngx.now()
local now = bson.get_utc_date(ngx_now * 1000)
local db = conn:new_db_handle('test')
local col = db:get_col('users')
local doc = { createdAt = now, username = 'test', password = ngx.md5('123456') }
ok, err = col:insert({doc}, true, true)
if not ok then
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.say('Failed : '.. err)
ngx.exit(ngx.status)
end
local date_fmt = string.format('!%%Y-%%m-%%dT%%T.%03dZ', now.v % 1000)
ngx.say(os.date(date_fmt, now.v/1000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment