Coder Social home page Coder Social logo

lua-mongo's Introduction

MongoDB Driver for Lua

lua-mongo is a binding to MongoDB C Driver 1.16 or higher for Lua:

  • Unified API for MongoDB commands, CRUD operations and GridFS in MongoDB C Driver.
  • Support for data transformation metamethods/handlers when converting to/from BSON documents.
  • Transparent conversion from Lua/JSON to BSON for convenience.
  • Automatic conversion of Lua numbers to/from BSON Int32, Int64 and Double types depending on their capacity without precision loss (when Lua allows it). Manual conversion is also available.

Dependencies

  • lua >= 5.1 (or luajit)
  • mongo-c-driver >= 1.16

Building and installing with LuaRocks

To build and install, run:

luarocks make

To install the latest release using luarocks.org, run:

luarocks install lua-mongo

Building and installing with CMake

To build and install, run:

cmake .
make
make install

To build for a specific Lua version, set USE_LUA_VERSION. For example:

cmake -D USE_LUA_VERSION=5.1 .

or for LuaJIT:

cmake -D USE_LUA_VERSION=jit .

To build in a separate directory, replace . with a path to the source.

To check your build, run:

make test

A local MongoDB server at mongodb://127.0.0.1 will be used for testing by default. Test settings can be configured in test/test.lua.

Getting started

Preparing the playground:

local mongo = require 'mongo'
local client = mongo.Client('mongodb://127.0.0.1')
local collection = client:getCollection('lua-mongo-test', 'test')
collection:drop() -- Clear collection

-- Common variables
local id = mongo.ObjectID()
local query1 = mongo.BSON('{ "age" : { "$gt" : 25 } }')
local query2 = mongo.BSON{_id = id}

Basic features and operations:

-- Implicit Lua/JSON to BSON conversion where BSON is required
collection:insert{_id = id, name = 'John Smith', age = 50}
collection:insert('{ "name" : "Bobby", "age" : 3 }')

-- Iterate documents in a for-loop
for person in collection:find({}, {sort = {age = -1}}):iterator() do
    print(person.name, person.age)
end

-- Fetch single document
local person = collection:findOne(query1):value()
print(person.name, person.age)

-- Access to BSON where needed
local bson = collection:findOne(query1)
print(bson) -- BSON is converted to JSON using tostring()

-- Explicit BSON to Lua conversion
local person = bson:value()
print(person.name, person.age)

-- Transparently include BSON documents in other documents
collection:update(query2, {age = 60, old = bson}) -- Update document
collection:remove(query2) -- Remove document

Bulk write operations can be used to execute multiple insert, update, replace and remove operations together. Executing write operations in batches reduces the number of network round trips increasing write throughput.

local bulk = collection:createBulkOperation()

-- Multiple insertions
bulk:insert{a = 1}
bulk:insert{b = 2}
bulk:insert{c = 3}

-- Multiple modifications
bulk:replaceOne({a = 1}, {b = 1})
bulk:updateMany('{}', '{ "$inc" : { "b" : 2 } }')
bulk:removeOne{c = 3}

-- Execute queued operations
bulk:execute()

The use of __toBSON metamethods and BSON handlers gives full control over how Lua values are represented in BSON documents and vice versa. In particular, this API facilitates support for Lua classes (tables with metatables) on their way to and/or from MongoDB.

local TestClass = {} -- Class metatable

local function TestObject(id, name) -- Constructor
    local object = {
        id = id,
        name = name,
    }
    return setmetatable(object, TestClass)
end

function TestClass:__tostring() -- Method
    return tostring(self.id) .. ' --> ' .. self.name
end

function TestClass:__toBSON() -- Called when object is serialized into BSON
    return {
        _id = self.id,
        binary = mongo.Binary(self.name), -- Store 'name' as BSON Binary for example
    }
end

-- A root '__toBSON' metamethod may return a table or BSON document.
-- A nested '__toBSON' metamethod may return a value, BSON type or BSON document.

-- BSON handler
local function handler(document)
    local id = document._id
    local name = document.binary:unpack() -- Restore 'name' from BSON Binary
    return TestObject(id, name)
end

-- Note that the same handler is called for each document. Thus, the handler should be able
-- to differentiate documents based on some internal criteria.

local object = TestObject(id, 'abc')
print(object)

-- Explicit BSON <-> Lua conversion
local bson = mongo.BSON(object)
local object = bson:value(handler)
print(object)

-- Store object
collection:insert(object)

-- Restore object
local object = collection:findOne(query2):value(handler)
print(object)

-- Iterate objects in a for-loop
for object in collection:find(query2):iterator(handler) do
    print(object)
end

Check out the API Reference for more information.

See also the MongoDB Manual for detailed information about MongoDB commands and CRUD operations.

lua-mongo's People

Contributors

neoxic avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lua-mongo's Issues

The specified module could not be found?

Using:

lua 5.3.6
luarocks 3.9.1
gcc 12.2.1
windows 10 64

Installing lua-mongo using luarocks

Installing https://luarocks.org/lua-mongo-1.2.3-2.src.rock

lua-mongo 1.2.3-2 depends on lua >= 5.1 (5.3-1 provided by VM)
gcc -O2 -c -o src/bson.o -IC:\lua\include src/bson.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/bsontype.o -IC:\lua\include src/bsontype.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/bulkoperation.o -IC:\lua\include src/bulkoperation.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/client.o -IC:\lua\include src/client.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/collection.o -IC:\lua\include src/collection.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/cursor.o -IC:\lua\include src/cursor.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/database.o -IC:\lua\include src/database.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/flags.o -IC:\lua\include src/flags.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/gridfs.o -IC:\lua\include src/gridfs.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/gridfsfile.o -IC:\lua\include src/gridfsfile.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/gridfsfilelist.o -IC:\lua\include src/gridfsfilelist.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/main.o -IC:\lua\include src/main.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/objectid.o -IC:\lua\include src/objectid.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/readprefs.o -IC:\lua\include src/readprefs.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc -O2 -c -o src/util.o -IC:\lua\include src/util.c -IC:\Program Files (x86)\mongo-c-driver/include/libmongoc-1.0 -IC:\Program Files (x86)\mongo-c-driver/include/libbson-1.0
gcc  -shared -o mongo.dll src/bson.o src/bsontype.o src/bulkoperation.o src/client.o src/collection.o src/cursor.o src/database.o src/flags.o src/gridfs.o src/gridfsfile.o src/gridfsfilelist.o src/main.o src/objectid.o src/readprefs.o src/util.o -LC:\Program Files (x86)\mongo-c-driver/lib -LC:\Program Files (x86)\mongo-c-driver/lib -lmongoc-1.0 -lbson-1.0 C:\lua\lib/lua53.dll -lm
lua-mongo 1.2.3-2 is now installed in C:\Users\useradmin\AppData\Roaming/luarocks (license: MIT)

Seems to work great. No errors in installation and a mongo.dll file is generated.

When opening lua:

Lua 5.3.6  Copyright (C) 1994-2020 Lua.org, PUC-Rio
> local m = require('mongo')
error loading module 'mongo' from file 'C:/Users/useradmin/AppData/Roaming/luarocks/lib/lua/5.3/mongo.dll':
        The specified module could not be found.

stack traceback:
        [C]: in ?
        [C]: in function 'require'
        stdin:1: in main chunk
        [C]: in ?

double checking path loader

> package.cpath
C:/lua/?.dll;C:/lua/../lib/lua/5.3/?.dll;C:/lua/loadall.dll;./?.dll;C:/lua/?53.dll;./?53.dll;C:/Users/useradmin/AppData/Roaming/luarocks/lib/lua/5.3/?.dll

The file is there.

sspivey@saspivey98:/mnt/c/Users/useradmin/appdata/roaming/luarocks/lib/lua/5.3$ ll | grep mongo
-rwxrwxrwx 1 sspivey sspivey  197698 Oct 12 14:38 mongo.dll*

I'm out of leads trying to figure out what is wrong here...

I builde lua-mongo success, But there is something wrong with the use

build mongo-c-driver 1.15 with luarock
-rwxr-xr-x 1 root root 93680 Nov 1 11:01 mongo.so
drwxr-xr-x 2 root root 53 Mar 27 2019 socket
[root@centos01 5.3]# ldd mongo.so
linux-vdso.so.1 => (0x00007ffc6fbec000)
libmongoc-1.0.so.0 => not found
libbson-1.0.so.0 => /usr/local/lib/libbson-1.0.so.0 (0x00007f0fbcc30000)
libc.so.6 => /lib64/libc.so.6 (0x00007f0fbc86d000)
libm.so.6 => /lib64/libm.so.6 (0x00007f0fbc56b000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f0fbc34e000)
/lib64/ld-linux-x86-64.so.2 (0x00007f0fbd082000)

problem is
error : ...ect/LinuxLua/AgentServer/build/lua/5.3/include/mongo.lua:1: module 'bson' not found:
no field package.preload['bson']
no file './lua/bson.lua'
no file '/usr/local/share/lua/5.3/bson.lua'
no file '/usr/local/share/lua/5.3/bson/init.lua'
no file '/usr/local/lib/lua/5.3/bson.lua'
no file '/usr/local/lib/lua/5.3/bson/init.lua'
no file './bson.lua'
no file './bson/init.luabson.lua'
no file '/data/project/LinuxLua/AgentServer/build/lua/5.3/include/bson.lua'
no file '/usr/local/lib/lua/5.3/bson.so'
no file '/usr/local/lib/lua/5.3/loadall.so'
no file './bson.sobson.so'
no file '/data/project/LinuxLua/AgentServer/build/lua/5.3/lib/bson.so'
stack[0] -> line -1 : unknown[[C] : line -1]
stack[1] -> line -1 : require()[[C] : line -1]
stack[2] -> line 1 : unknown[...ect/LinuxLua/AgentServer/build/lua/5.3/include/mongo.lua : line 0]
stack[3] -> line -1 : require()[[C] : line -1]
stack[4] -> line 78 : unknown[./lua/testmongo.lua : line 0]
stack[5] -> line -1 : require()[[C] : line -1]
stack[6] -> line 146 : unknown[lua/ManagerTest.lua : line 0]

I build and use in window is ok ,but linux is wrong!! why??
filename diffance?

Support for Multi-field Sorting in find Method

Please note that lua-mongo is merely a binding to Mongo C Driver. It neither adds nor subtracts anything within the supported API.

Before reporting an issue, please make sure the problem is with lua-mongo itself rather than with MongoDB syntax or the Mongo C Driver API by checking the following links:

MongoDB operators

Mongo C Driver API

Issues unrelated to lua-mongo will be closed without a warning.


Title: Support for Multi-field Sorting in find Method

Description:

Hi,

First of all, thank you for your great work on this library. I really appreciate it!

I have a question regarding the usage of the find method with multi-field sorting. In the README documentation, I found an example like this:

collection:find('{ "_id" : { "$gt" : 123 } }', {sort = {_id = -1}}):iterator()

However, in my practice, I want to use something like:

{sort = {field1 = -1, field2 = -1}}

This means I want to sort by field1 in descending order as the first order and by field2 in descending order as the second order.

When I use it like this, there is no error in running the code, but the order returned from the find method doesn't seem to apply these sort rules.

Does this library support usage like this? If not, could you please consider adding support for multi-field sorting in the find method? Please let me know if there is anything I can help.

Thank you!


Support Connection Pooling

Could this library support Connection Pooling?

http://mongoc.org/libmongoc/current/connection-pooling.html#connection-pooling
http://mongoc.org/libmongoc/current/mongoc_client_pool_t.html

mongoc_client_pool_t
mongoc_client_pool_pop
mongoc_client_pool_push
mongoc_client_pool_set_error_api

The following method may be also needed for gc?
mongoc_client_pool_destroy (pool);
mongoc_uri_destroy (uri);

mongoc_cleanup ();

Here is the other mongoc binding driver in ffi, for your reference.
https://github.com/lloydzhou/luajit-mongo/blob/master/mongo.lua


Thanks.

undefined symbol: mongoc_collection_replace_one

error during loading module:

[error] 12528#12528: *4392626 lua entry thread aborted: runtime error: error loading module 'mongo' from file '/usr/local/openresty/lualib/mongo.so':
        /usr/local/openresty/lualib/mongo.so: undefined symbol: mongoc_collection_replace_one

Install error

# cat /etc/redhat-release 
CentOS Linux release 7.8.2003 (Core)
# lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
>
# luarocks install lua-mongo LIBBSON_INCDIR=/usr/include/ LIBMONGOC_INCDIR=/usr/include/
Warning: falling back to curl - install luasec to get native HTTPS support
Installing https://luarocks.org/lua-mongo-1.2.2-1.src.rock...
Using https://luarocks.org/lua-mongo-1.2.2-1.src.rock... switching to 'build' mode
gcc -O2 -fPIC -I/usr/include -c src/bson.c -o src/bson.o -I/usr/include//libmongoc-1.0 -I/usr/include//libbson-1.0
src/bson.c: In function ‘initBSON’:
src/bson.c:144:2: warning: passing argument 1 of ‘memcpy’ makes pointer from integer without a cast [enabled by default]
  memcpy(bson_reserve_buffer(bson, len), str, len);
  ^
In file included from /usr/include//libbson-1.0/bson-compat.h:80:0,
                 from /usr/include//libbson-1.0/bson.h:23,
                 from /usr/include//libmongoc-1.0/mongoc/mongoc.h:22,
                 from src/common.h:26,
                 from src/bson.c:23:
/usr/include/string.h:42:14: note: expected ‘void * __restrict__’ but argument is of type ‘int’
 extern void *memcpy (void *__restrict __dest, const void *__restrict __src,
              ^
src/bson.c: In function ‘appendBSONType’:
src/bson.c:163:8: error: ‘BSON_TYPE_DECIMAL128’ undeclared (first use in this function)
   case BSON_TYPE_DECIMAL128: {
        ^
src/bson.c:163:8: note: each undeclared identifier is reported only once for each function it appears in
src/bson.c:165:4: error: unknown type name ‘bson_decimal128_t’
    bson_decimal128_t dec;

Why I can't install lua-mongo?

Lua-mongo can't be used with mongo-c-driver_v1.19

image

code:

local client = mongo.Client(...)
local coll = client:getCollection("team", "mytest")
coll:insert('{ "name" : "Bobby", "age" : 23 }')

The code running environment is OpenResty .

error:
*** Error in `nginx: worker process': free(): invalid next size (fast): 0x0000000002135360 ***
2021/11/14 20:38:06 [alert] 91383#91383: worker process 51751 exited on signal 11

nginx content_by_lua_block gives an error if ssl is used

If I use this package stand alone under lua or luajit everthing works fine.
If I use code under nginx

content_by_lua_block {           
             local mongo = require 'mongo'
             ...
}

the it gives an error
2020/10/09 08:06:23 [error] 1421#0: *51 lua entry thread aborted: runtime error: content_by_lua(nginx-kong.conf:283):24: No suitable servers found (serverSelectionTryOnce set): [TLS handshake failed: error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed calling ismaster on 'cluster0-shard-00-00.6h6bl.mongodb.net:27017'] [TLS handshake failed: error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed calling ismaster on 'cluster0-shard-00-01.6h6bl.mongodb.net:27017'] [TLS handshake failed: error:1416F086:SSL routines:tls_process_server_certificate:certificate

No error if SSL is not used. Plain mongodb://foo works fine.

Compile error

In file collections.c at line 125:
int i, n = lua_gettop(L) - 1;
bson_t const *documents[n];

the [n] causes Error C2057 expected constant expression lua-mongo C:\work\lua-mongo\src\collection.c 125
with Visual Studio 2019. msvc does not support VLA, which is C99.

cant get build via luarocks in windows

trying to build lua-mongo. i did download mongo-c-driver and make folders in c:\external\include\libbson-1.0 and c:\external\includelibmongoc-1.0. first i getting error that there is no bson-config.h

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community>luarocks install lua-mongo
Installing https://luarocks.org/lua-mongo-1.2.2-1.src.rock

lua-mongo 1.2.2-1 depends on lua >= 5.1 (5.3-1 provided by VM)
cl /nologo /MD /O2 -c -Fosrc/bson.obj -IC:\luarocks/include src/bson.c -Ic:/external/include/libmongoc-1.0 -Ic:/external/include/libbson-1.0
bson.c
c:\external\include\libbson-1.0\bson\bson-compat.h(34): fatal error C1083: Cannot open include file: 'bson-config.h': No such file or directory

Error: Build error: Failed compiling object src/bson.obj

then i tried to rename bson-config.h.in TO bson-config.h in libbson folder and then i getting this error

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community>luarocks install lua-mongo
Installing https://luarocks.org/lua-mongo-1.2.2-1.src.rock

lua-mongo 1.2.2-1 depends on lua >= 5.1 (5.3-1 provided by VM)
cl /nologo /MD /O2 -c -Fosrc/bson.obj -IC:\luarocks/include src/bson.c -Ic:/external/include/libmongoc-1.0 -Ic:/external/include/libbson-1.0
bson.c
c:\external\include\libbson-1.0\bson\bson-compat.h(34): fatal error C1083: Cannot open include file: 'bson-config.h': No such file or directory

Error: Build error: Failed compiling object src/bson.obj

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community>luarocks install lua-mongo
Installing https://luarocks.org/lua-mongo-1.2.2-1.src.rock

lua-mongo 1.2.2-1 depends on lua >= 5.1 (5.3-1 provided by VM)
cl /nologo /MD /O2 -c -Fosrc/bson.obj -IC:\luarocks/include src/bson.c -Ic:/external/include/libmongoc-1.0 -Ic:/external/include/libbson-1.0
bson.c
c:\external\include\libbson-1.0\bson\bson-config.h(34): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(52): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(60): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(69): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(78): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(87): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(96): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(105): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(114): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(123): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(132): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(141): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(146): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-config.h(151): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-macros.h(33): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-macros.h(35): error C2018: unknown character '0x40'
c:\external\include\libbson-1.0\bson\bson-macros.h(38): fatal error C1189: #error:  "Unknown operating system."

Error: Build error: Failed compiling object src/bson.obj

so what should i do to build lua-mongo??

`mongo.BSON {a={1,2,3}}` segfaults

The following

mongo.BSON {a={__array, 1, 2, 3}}

segfaults, as well as the syntax in title. At least, an error, rather than a segfault, shall be issued by Lua.

i have problem guy.how to find or aggregation ISODate.

i try.
in mongo db
{"start_time" : ISODate("2020-09-18T17:57:20Z"),"exp_time" : ISODate("2021-09-07T17:57:20Z")}
how to find or aggregation time with gte or lte
i use query in mongo shell it work .
db.collection.find({ "start_time" : { "$lte": ISODate("2020-09-18T17:57:20Z")} })

how to find isodate in your lib

thank you.

Requiring the library from Lua results in error ("undefined symbol: lua_tointeger")

Title is pretty much self-explanatory; the line local mongo = require 'mongo' will result in a crash saying the following :

lua: error loading module 'mongo' from file '/usr/local/lib/lua/5.2/mongo.so':
	/usr/local/lib/lua/5.2/mongo.so: undefined symbol: lua_tointeger
stack traceback:
	[C]: in ?
	[C]: in function 'require'
	test/test-mongo.lua:1: in main chunk
	[C]: in ?

It does that on the test files given in the test/ folder, as well as a dummy lua script with only the faulty line in it.

I'm running Ubuntu 19.10 and I'm using Lua 5.2. I compiled the driver with CMake.

Note : the compiler gave me some trouble (I had to specify that I was using Lua 5.2, and it said : -- Using Lua '5.2', version 5.1.5), not sure if it's related.

Thanks in advance!

Openrety nginx log show '2018/08/17 23:37:54 [notice] 2603#2603: signal 17 (SIGCHLD) received from 2604 2018/08/17 23:37:54 [notice] 2603#2603: worker process 2604 exited with code 0 2018/08/17 23:37:54 [notice] 2603#2603: exit'

When I execute 'local mongo = require("mongo")'. The nginx logs show as blow.

2018/08/17 23:37:54 [notice] 2603#2603: signal 17 (SIGCHLD) received from 2604
2018/08/17 23:37:54 [notice] 2603#2603: worker process 2604 exited with code 0
2018/08/17 23:37:54 [notice] 2603#2603: exit

I have a clean centos 7.3. install newest openresty. Use the newest cmake and mongo-c-driver to build the mongo.so.

Session support

Hey,

I've been looking at the code you implemented and, first of all, thanks for all the work.
Now, I have a task at hand where I need to use a transaction to create multiple collections and commit or abort depending on the jobs' success. This should be available on the latest mongo version (4.4), so I went searching for the class in your code where the notion of transaction or session was implemented. Unfortunately, I didn't find them.

Am I missing something? Or, if not, are you planning on implementing these notions soon?

Here's the documentation I've been looking at:

Thanks in advance.

have a question

How to use MongoDB's projection to select some fields? I only saw query and options findOne(query,options)

client connection error handling

Is there a way to find out if and/or why the mongo client connection failed? I see that when I do a mongo.Client() call, I get a return value even if the connection to the database failed. Even if I put it a incorrect URI, I still get a client connection value returned, but it does not work and at the same time there are no errors.

local uri = 'mongodb://1274.8398.433.344' -- or correct but inaccessible database URI
local client = mongo.Client()
local collection = client:getCollection('mail', 'data')

  collection:insert{
      key = value
  }

This will run fine with no errors even though uri is not correct or if for some reason connection to the URI fails. Is there any way to get an error back?

Trying to retrieve the server date with serverStatus

I am unable to find the syntax that will give me the serverStatus and so the Date of the server.

I have tried something like

ret = client:command("myDb",' { "serverStatus' : 1 } ' )
but ret is not a document

In the database methods documentation there is no database:serverStatus() as I would expect

Thanks a lot for any help

How to auth by mongo use luamongo?

Please note that lua-mongo is merely a binding to Mongo C Driver. It neither adds nor subtracts anything within the supported API.

Before reporting an issue, please make sure the problem is with lua-mongo itself rather than with MongoDB syntax or the Mongo C Driver API by checking the following links:

MongoDB operators

Mongo C Driver API

Issues unrelated to lua-mongo will be closed without a warning.


undefined symbol: mongoc_database_drop_with_opts

Hi,

libmongoc-1.0-0
1.9.3+dfsg-2

lua-mongo
1.0.0-1 (installed) - /usr/local/lib/luarocks/rocks

Got this error when trying to load the driver
local mongo = require 'mongo'

lua: error loading module 'mongo' from file '/usr/local/lib/lua/5.1/mongo.so':
        /usr/local/lib/lua/5.1/mongo.so: undefined symbol: mongoc_database_drop_with_opts

by the way does it support replica set?

Thanks,
Arsen

Unable to install lua-mongo with luarocks

I'm getting an error when I try to install lua-mongo with luarocks.
image

Installing https://luarocks.org/lua-mongo-1.2.2-1.src.rock gcc -O2 -fPIC -I/usr/include/lua5.2 -c src/bson.c -o src/bson.o -I/usr/local/include/libmongoc-1.0 -I/usr/local/include/libbson-1.0 In file included from src/bson.c:23: src/common.h:25:10: fatal error: lauxlib.h: No such file or directory #include <lauxlib.h> ^~~~~~~~~~~ compilation terminated.

I installed the mongo-c driver version 1.17.3 following these steps:
$ wget https://github.com/mongodb/mongo-c-driver/releases/download/1.17.3/mongo-c-driver-1.17.3.tar.gz $ tar xzf mongo-c-driver-1.17.3.tar.gz $ cd mongo-c-driver-1.17.3 $ mkdir cmake-build $ cd cmake-build $ cmake -DENABLE_AUTOMATIC_INIT_AND_CLEANUP=OFF .. $ make $ sudo make install

How to install on Windows?

I tried luarocks + vcpkg but I can't get it to work.

This is how I call it:

luarocks install lua-mongo LIBBSON_INCDIR=C:\g\vcpkg\packages\libbson_x86-windows LIBMONGOC_INCDIR=C:\g\vcpkg\packages\mongo-c-driver_x86-windows

output below

src/collection.c(125): error C2057: expected constant expression
src/collection.c(125): error C2466: cannot allocate an array of constant size 0
src/collection.c(125): error C2133: 'documents': unknown size

Error: Build error: Failed compiling object src/collection.obj

i have question.How to limit bro.

how to limit guy. thank you.

#!/usr/bin/env lua
local mongo = require 'mongo'
local client = mongo.Client('mongodb://127.0.0.1')
local collection = client:getCollection('db', 'test_col')

for person in collection:find({},{sort = {age = -1}}):iterator() do
    print(person.name)
end

$sort operator

Hi all,
Is there a chance to have got the $sort operator for query option or as a cursor method?
For my understanding, your project doesn't support server side sorting. Does it?
Thank you.
R.

c89 compatibility (fixed)

I had to make some minor changes to get it to compile on a c89 compiler. See attached file
diff.txt
.

I also had to change the name of bson.c since the same file name is in the Mongo C driver: mongoc.org

the positional $ operator seems to be not suported

We try to use the notation $ to select all the array value in the projection but this notation seems to be not implemented !
the string is :

str=string.format([[
[
                { "$match": 
                               {
                                               "Code_IG":"6546544",
                                               "POS.freq":"474"
                               }
                } ,
                { "$projecti": 
                               { 
                                               "clientID":1,
                                               "POS.$":1,
                                               "_idques":0 
                               }
                }
]
]])query=mongo.BSON(str)
loop=collection:aggregate(query):value();
if loop then
OP_Display_mongo_list("document",loop);
End
```

Installing 32 bit version lib?

Hey,

I am trying to use the lua-mongo, although getting the following error:

LUA ERROR: error loading module 'mongo' from file '/usr/local/lib/lua/5.1/mongo.so': /usr/local/lib/lua/5.1/mongo.so: wrong ELF class: ELFCLASS64

As far as I googled it, it seems that my version is 64 bit, but I am trying to run it on a 32 bit program, right?

At least the program where I am using (CS2D) is 32 Bit (and LUA 5.1)

How to insert Int64 data type into mongo ?

Hello,

When I insert an Integer into mongoDB it's displayed as Int32.
Could someone please tell me how to add the field startDate as Int64 ?

local myCollection = client:getCollection('testDB', 'conferences')

local conference = {
   name = "test",
   numberOfParticipants = 0,
   startDate = os.time()
};

myCollection:insert(json.encode(conference))

Thanks for your help!

how to use "{allowDiskUse: true }" in aggregate guy ?

i have more document more than 1000000 . cannot use allowDiskUse.

for data_output in collection2:aggregate('[{"$group" : { "_id": "$num", "count": { "$sum": 1 } } },{"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, {"$project": {"num" : "$_id", "_id" : "$count"} },{"$sort":{"_id":-1}}],{"allowDiskUse": true}'):iterator() do
    print(data_output)
   return 0
end

error = Each element of the 'pipeline' array must be an object

thank you neoxic.

SegFault in tests

mac os 10.13.3
mongo-c-driver: stable 1.9.3

pachin:/Users/pachin/Work/SRV/lua-mongo>cmake -D USE_LUA_VERSION=5.1 .
-- Checking for one of the modules 'lua-5.1;lua5.1;lua51'
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/pachin/Work/SRV/lua-mongo
pachin:/Users/pachin/Work/SRV/lua-mongo>make
Scanning dependencies of target mongo
[  6%] Building C object CMakeFiles/mongo.dir/src/bson.c.o
[ 13%] Building C object CMakeFiles/mongo.dir/src/bsontype.c.o
[ 20%] Building C object CMakeFiles/mongo.dir/src/bulkoperation.c.o
[ 26%] Building C object CMakeFiles/mongo.dir/src/client.c.o
[ 33%] Building C object CMakeFiles/mongo.dir/src/collection.c.o
[ 40%] Building C object CMakeFiles/mongo.dir/src/cursor.c.o
[ 46%] Building C object CMakeFiles/mongo.dir/src/database.c.o
[ 53%] Building C object CMakeFiles/mongo.dir/src/flags.c.o
[ 60%] Building C object CMakeFiles/mongo.dir/src/gridfs.c.o
[ 66%] Building C object CMakeFiles/mongo.dir/src/gridfsfile.c.o
[ 73%] Building C object CMakeFiles/mongo.dir/src/gridfsfilelist.c.o
[ 80%] Building C object CMakeFiles/mongo.dir/src/main.c.o
[ 86%] Building C object CMakeFiles/mongo.dir/src/objectid.c.o
[ 93%] Building C object CMakeFiles/mongo.dir/src/util.c.o
[100%] Linking C shared library mongo.so
[100%] Built target mongo
pachin:/Users/pachin/Work/SRV/lua-mongo>make test
Running tests...
Test project /Users/pachin/Work/SRV/lua-mongo
    Start 1: test-bson.lua
1/3 Test #1: test-bson.lua ....................***Exception: SegFault  0.08 sec
    Start 2: test-gridfs.lua
2/3 Test #2: test-gridfs.lua ..................***Exception: SegFault  1.21 sec
    Start 3: test-mongo.lua
3/3 Test #3: test-mongo.lua ...................***Exception: SegFault  0.11 sec

0% tests passed, 3 tests failed out of 3

Total Test time (real) =   1.43 sec

The following tests FAILED:
	  1 - test-bson.lua (SEGFAULT)
	  2 - test-gridfs.lua (SEGFAULT)
	  3 - test-mongo.lua (SEGFAULT)
Errors while running CTest
make: *** [test] Error 8

i cann't query.have problem.

Hi neoxic. I ahve problem.Iwant query this .
mongo shell i want.
db.test.find({"$and":[{"num":{"$exists":true}},{"num":{"$nin":[0]}}]}).sort({num:1}).limit(1)
i try query in
local query_max = mongo.BSON('{"$and":[{"num":{"$exists":true}},{"num":{"$nin":[0]}}]},{"limit":5}')

for select_data in collection:find(query_max):iterator() do
            print(select_data.num)
  end

respon = {}
help pls neoxic.I think syntax me error.but i don't know guy.
thank you.

Process aborts due to a zero server_id

Make sure that you actually have database TestDatabase with collection TestCollection which contains 101+ documents:

local mongo = require 'mongo'
local client = mongo.Client('mongodb://127.0.0.1')
local cmd = {find = "TestCollection"}
local cursor = client:command("TestDatabase", cmd)
return type(cursor)

The process will abort due to failed assertion BSON_ASSERT (server_id); inside mongoc_cluster_stream_for_server() in mongoc-cluster.c: mongoc_cluster_stream_for_server(): precondition failed: server_id

This seems to happen only if the data of firstBatch isn't fully consumed:

local count = 0
for _ in cursor:iterator() do
	count = count + 1
	if count == 102 then break end -- any value smaller than 102 will abort
end
return count

lua-mongo: v1.2.0
mongo-c-driver: v1.15.1

undefined symbol: mongoc_collection_count_documents

When I try to:
local mongo = require "mongo"

I get an error:

[error] 17939#17939: *764940 lua entry thread aborted: runtime error: error loading module 'mongo' from file '/usr/local/lib/lua/5.1/mongo.so':
        /usr/local/lib/lua/5.1/mongo.so: undefined symbol: mongoc_collection_count_documents

How to fix this?

# cat /etc/lsb-release 
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=18.04
DISTRIB_CODENAME=bionic
DISTRIB_DESCRIPTION="Ubuntu 18.04.3 LTS"

Cannot create bson document with array indexed by numbers

Hello

It looks like it is not possible to create bson document with number indexed arrays:

lua: mongotest.lua:5: bad argument #1 to 'BSON' (["path"] => string index expected, got number)
stack traceback:
        [C]: in function 'BSON'
        mongotest.lua:5: in main chunk
        [C]: ?

test:

local mongo = require 'mongo'
--works
mongo.BSON{ path = { ["1"]="a", ["2"]="b", ["3"]="c", }}
--fails
mongo.BSON{ path = { "a", "b", "c" } }

Find method how to select the specified column?

Please note that lua-mongo is merely a binding to Mongo C Driver. It neither adds nor subtracts anything within the supported API.

Before reporting an issue, please make sure the problem is with lua-mongo itself rather than with MongoDB syntax or the Mongo C Driver API by checking the following links:

MongoDB operators

Mongo C Driver API

Issues unrelated to lua-mongo will be closed without a warning.


I have problem with luarocks install lua-mongo.

I have problem with luarocks install lua-mongo.
I install luarocks install lua-mongo. Have problem. help me please. thank you.
I've already installed bson lib.

Installing https://luarocks.org/lua-mongo-1.2.1-1.src.rock

Error: Could not find header file for LIBBSON
No file libbson-1.0/bson/bson.h in /usr/local/include
No file libbson-1.0/bson/bson.h in /usr/include
You may have to install LIBBSON in your system and/or pass LIBBSON_DIR or LIBBSON_INCDIR to the luarocks command.
Example: luarocks install lua-mongo LIBBSON_DIR=/usr/local

How to create a TTL index?

Can I create a TTL index with a lua-mango package?
If it is possible can you please me how in sort?

This is one of the excellent tools that I found for lua mongo connectivity.

I really appreciate any help you can provide.

building with luarocks mingw64

I downloaded the mongo-c-driver 1.16 binaries and built it using mingw64 MSYS Makefiles and gcc 12.2.1 on windows 10, 64-bit.

run this command in luarocks 3.3.1:

luarocks install lua-mongo LIBBSON_DIR=C:\lua LIBMONGOC_DIR=C:\lua

this what is returned:

Installing https://luarocks.org/lua-mongo-1.2.3-1.src.rock

lua-mongo 1.2.3-1 depends on lua >= 5.1 (5.3-1 provided by VM)
gcc -O2 -c -o src/bson.o -IC:\lua\include src/bson.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/bsontype.o -IC:\lua\include src/bsontype.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/bulkoperation.o -IC:\lua\include src/bulkoperation.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/client.o -IC:\lua\include src/client.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/collection.o -IC:\lua\include src/collection.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/cursor.o -IC:\lua\include src/cursor.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/database.o -IC:\lua\include src/database.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/flags.o -IC:\lua\include src/flags.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/gridfs.o -IC:\lua\include src/gridfs.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/gridfsfile.o -IC:\lua\include src/gridfsfile.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/gridfsfilelist.o -IC:\lua\include src/gridfsfilelist.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/main.o -IC:\lua\include src/main.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/objectid.o -IC:\lua\include src/objectid.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/readprefs.o -IC:\lua\include src/readprefs.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -O2 -c -o src/util.o -IC:\lua\include src/util.c -IC:\lua/include/libmongoc-1.0 -IC:\lua/include/libbson-1.0
gcc -shared -o mongo.dll src/bson.o src/bsontype.o src/bulkoperation.o src/client.o src/collection.o src/cursor.o src/database.o src/flags.o src/gridfs.o src/gridfsfile.o src/gridfsfilelist.o src/main.o src/objectid.o src/readprefs.o src/util.o -LC:\lua -LC:\lua -lmongoc-1.0 -lbson-1.0 C:\lua\lib/lua53.dll -lm
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lmongoc-1.0: No such file or directory
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lbson-1.0: No such file or directory
collect2.exe: error: ld returned 1 exit status

Error: Build error: Failed compiling module mongo.dll

I genuinely don't know what -lmongoc-1.0 and -lbson-1.0 dependencies are referencing.
Sorry if this is not the right place, I realize this is more a luarocks question.

insertOne question

Why does insertone not return reply?
I want to win_ id
Sorry, I can't speak English. This is from machine translation.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.