Module ejdb
The Lua binding of EJDB database.
http://ejdb.org
Usage:
-- File: samples/sample1.lua local ejdb = require("ejdb") local inspect = require("ejdb.inspect") local Q = ejdb.Q -- Used modes: -- 'r' - read -- 'w' - write -- 'c' - create db if not exists -- 't' - truncate existing db local db = ejdb.open("zoo", "rwct") -- Unordered lua table local parrot1 = { name = "Grenny", type = "African Grey", male = true, age = 1, birthhdate = ejdb.toDateNow(), likes = { "green color", "night", "toys" }, extra1 = ejdb.toNull() } -- Preserve order of BSON keys local parrot2 = Q(); parrot2:KV("name", "Bounty"):KV("type", "Cockatoo"):KV("male", false) parrot2:KV("age", 15):KV("birthdate", ejdb.toDate({ year = 2013, month = 1, day = 1, hour = 0, sec = 1 })) parrot2:KV("likes", { "sugar cane" }):KV("extra1", ejdb.toNull()) --IF YOU WANT SOME DATA INSPECTIONS: --print(ejdb.print_bson(parrot2:toBSON())) --local obj = ejdb.from_bson(parrot2:toBSON()) --print(inspect(obj)); db:save("parrots2", parrot1) db:save("parrots2", parrot2) -- Below two equivalent queries: -- Q1 local res, count, log = db:find("parrots2", Q("likes", "toys"):OrderBy("name asc", "age desc")) for i = 1, #res do -- iterate one local ob = res:object(i) print("" .. ob["name"] .. " likes toys #1") end -- Q2 local res, count, log = db:find("parrots2", Q():F("likes"):Eq("toys"):OrderBy({ name = 1 }, { age = -1 })) for i = 1, #res do -- iterate one print("" .. res:field(i, "name") .. " likes toys #2") end -- Second way to iterate for vobj, idx in res() do print("" .. vobj["name"] .. " likes toys #3") end db:close()
Functions
open (path, mode) | Opens EJDB database. |
close () | Closes opened database. |
toOID (val) | Converts string OID into BSON oid table. |
toDate (val) | Converts os.time table (or number of seconds since epoch) into BSON_DATE. |
toDateNow () | Converts current time into BSON_DATE. |
toRegexp (re, opts) | Builds BSON_REGEX value |
toBinData (val) | Converts lua string into BSON_BINDATA value |
toNull () | Builds BSON_NULL value |
toUndefined () | Builds BSON_UNDEFINED value |
DB.toOID (val) | Converts string OID into BSON oid table. |
DB.toDate (val) | Converts os.time table or number of secods integer into BSON_DATE. |
DB.toDateNow () | Converts current time into BSON_DATE. |
DB.toRegexp (re, opts) | Builds BSON_REGEX value. |
DB.toBinData (val) | Converts lua string into BSON_BINDATA value. |
DB.toNull () | Builds BSON_NULL value. |
DB.toUndefined () | Builds BSON_UNDEFINED value . |
DB.version () | Returns EJDB version string eg: "1.1.14" |
DB:save (cname, obj, ...) | Save/update specified JSON objects in the collection. |
DB:load (cname, oid) | Loads JSON object identified by OID from the collection. |
DB:command (cmd) | Executes ejdb command. |
DB:find (cname, q, flags) | Execute query on collection. |
DB:findOne (cname, q) | Same as DB:find but retrieves only first matching JSON object. |
DB:update (cname, q) | Convenient method to execute update queries. |
DB:count (cname, q) | Convenient count(*) operation. |
DB:sync (cname) | Synchronize EJDB database with storage. |
DB:getDBMeta () | Get table object describes a database structure and its collections. |
DB:beginTransaction (cname) | Begin collection transaction. |
DB:commitTransaction (cname) | Commit collection transaction. |
DB:rollbackTransaction (cname) | Rollback collection transaction. |
DB:getTransactionStatus (cname) | Get collection transaction status. |
DB:dropIndexes (cname, fpath) | DROP indexes of all types for JSON field path. |
DB:optimizeIndexes (cname, fpath) | OPTIMIZE indexes of all types for JSON field path. |
DB:ensureStringIndex (cname, fpath) | Ensure index presence of String type for JSON field path. |
DB:rebuildStringIndex (cname, fpath) | Rebuild index of String type for JSON field path. |
DB:dropStringIndex (cname, fpath) | Drop index of String type for JSON field path. |
DB:ensureIStringIndex (cname, fpath) | Ensure case insensitive String index for JSON field path. |
DB:rebuildIStringIndex (cname, fpath) | Rebuild case insensitive String index for JSON field path. |
DB:dropIStringIndex (cname, fpath) | Drop case insensitive String index for JSON field path. |
DB:ensureNumberIndex (cname, fpath) | Ensure index presence of Number type for JSON field path. |
DB:rebuildNumberIndex (cname, fpath) | Rebuild index of Number type for JSON field path. |
DB:dropNumberIndex (cname, fpath) | Drop index of Number type for JSON field path. |
DB:ensureArrayIndex (cname, fpath) | Ensure index presence of Array type for JSON field path. |
DB:rebuildArrayIndex (cname, fpath) | Rebuild index of Array type for JSON field path. |
DB:rebuildArrayIndex (cname, fpath) | Drop index of Array type for JSON field path. |
RS:object (i) | Returns result set lua table object at specified position i |
RS:field (i, name) | Returns field value of lua object at specified position i |
RS.__len () | Length of result set. |
Q:KV (key, value) | Adds field into current JSON object. |
Q:F (fname) | Set current field for the next operation during query building. |
Q:Eq (val) | Field equality restriction. |
Q:ElemMatch (val) | Element match construction. |
Q:Not (val) | The $not negatiation for val block |
Q:Gt (val) | Greater than (val > arg) |
Q:Gte (val) | Greater than or equal (val >= arg) |
Q:Lt (val) | Lesser than (val < arg) |
Q:Lte (val) | Lesser than or equal (val <= arg) |
Q:Icase (val) | Case insensitive string matching |
Q:Begin (val) | String starts with prefix |
Q:In (val) | Field value matched any value of specified in val table. |
Q:NotIn (val) | Negation of Q:In |
Q:Bt (n1, n2) | Between for number types |
Q:StrAnd (val) | String tokens(or string array vals) matches all tokens in specified val array. |
Q:StrOr (val) | String tokens(or string array vals) matches any token in specified array. |
Q:Inc (val) | Increment current field. |
Q:Set (val) | Set fields to values. |
Q:Upsert (val) | Atomic upsert. |
Q:AddToSet (val) | Atomically adds val to the array field only if val not in the array already. |
Q:AddToSetAll (val) | Atomically performs set union with values in val for specified array field. |
Q:Pull (val) | Atomically removes all occurrences of val from field, if field is an array. |
Q:PullAll (val) | Atomically performs set substraction of values in val for specified array field. |
Q:DropAll () | In-place record removal operation. |
Q:Join (cname, fpath) | Make collection join for select queries. |
Q:Or (...) | Add OR joined query restrictions. |
Q:Skip (val) | Sets number of skipped records in the result set. |
Q:Max (val) | Sets max number of records in the result set. |
Q:OrderBy (...) | Set sorting rules for query results. |
Q:Fields (...) | Sets fields to be included in resulting objects. |
Q:NotFields (...) | Sets fields to be excluded from resulting objects. |
Tables
Q | Query/JSON builder is used to create EJDB queries or JSON objects with preserverd keys order (Unlike lua tables). |
DB | Database itself. |
RS | Result set cursor object. |
Functions
- open (path, mode)
-
Opens EJDB database.
Parameters:
- path string Database main file
- mode
optional string
Database open mode flags:
Open as a writerw
Open as a readerr
Create db if it not existsc
Truncate existing dbt
Sycn db after each transactions
Default open mode:rwcs
Returns:
-
Database table
Usage:
local db = ejdb.open("foodb", "wrc")
- close ()
- Closes opened database.
- toOID (val)
-
Converts string OID into BSON oid table.
Parameters:
- val string 24 hex chars BSON_OID
- toDate (val)
-
Converts os.time table (or number of seconds since epoch) into BSON_DATE.
Parameters:
- val
Returns:
-
BSON_DATE table.
Usage:
ejdb.toDate({ year = 2013, month = 1, day = 1, hour = 0, sec = 1 })
ejdb.toDate(1363705285431)
- toDateNow ()
- Converts current time into BSON_DATE.
- toRegexp (re, opts)
-
Builds BSON_REGEX value
Parameters:
Returns:
-
BSON_REGEX table value
- toBinData (val)
-
Converts lua string into BSON_BINDATA value
Parameters:
- val
Returns:
-
BSON_BINDATA table value
- toNull ()
-
Builds BSON_NULL value
Returns:
-
BSON_NULL table value
- toUndefined ()
-
Builds BSON_UNDEFINED value
Returns:
-
BSON_UNDEFINED table value
- DB.toOID (val)
-
Converts string OID into BSON oid table.
Parameters:
- val
see also:
- DB.toDate (val)
-
Converts os.time table or number of secods integer into BSON_DATE.
Parameters:
- val
see also:
- DB.toDateNow ()
-
Converts current time into BSON_DATE.
see also:
- DB.toRegexp (re, opts)
-
Builds BSON_REGEX value.
Parameters:
- re
- opts
see also:
- DB.toBinData (val)
-
Converts lua string into BSON_BINDATA value.
Parameters:
- val
see also:
- DB.toNull ()
-
Builds BSON_NULL value.
see also:
- DB.toUndefined ()
-
Builds BSON_UNDEFINED value .
see also:
- DB.version ()
- Returns EJDB version string eg: "1.1.14"
- DB:save (cname, obj, ...)
-
Save/update specified JSON objects in the collection.
If collection with
cname
does not exists it will be created. Each persistent object has unique identifier (OID) placed in the_id
property. If a saved object does not have_id
it will be autogenerated. To identify and update object it should contains_id
property. already persisted in db.Parameters:
- cname string Collection name.
- obj table or Q represents JSON object.
- ... If last argument is True a saved object will be merged with who's
Usage:
dQ:save("parrots2", {foo = "bar"})
dQ:save("parrots2", Q("foo", "bar"), true) -- merge option is on
- DB:load (cname, oid)
-
Loads JSON object identified by OID from the collection.
Parameters:
- DB:command (cmd)
-
Executes ejdb command. Supported commands:
1) Exports database collections data. See ejdbexport() method. "export" : { "path" : string, //Exports database collections data "cnames" : [string array]|null, //List of collection names to export "mode" : int|null //Values: null|`JBJSONEXPORT` See ejdb.h#ejdbexport() method } Command response: { "log" : string, //Diagnostic log about executing this command "error" : string|null, //ejdb error message "errorCode" : int|0, //ejdb error code } 2) Imports previously exported collections data into ejdb. "import" : { "path" : string //The directory path in which data resides "cnames" : [string array]|null, //List of collection names to import "mode" : int|null //Values: null|`JBIMPORTUPDATE`|`JBIMPORTREPLACE` See ejdb.h#ejdbimport() method } Command response: { "log" : string, //Diagnostic log about executing this command "error" : string|null, //ejdb error message "errorCode" : int|0, //ejdb error code }
Parameters:
Returns:
-
Command response table
- DB:find (cname, q, flags)
-
Execute query on collection.
EJDB queries inspired by MongoDB (mongodb.org) and follows same philosophy.
Queries and query hints can be constructed by Q query/json builder.
- Supported queries: - Simple matching of String OR Number OR Array value: - {'fpath' : 'val', ...} - $not Negate operation. - {'fpath' : {'$not' : val}} //Field not equal to val - {'fpath' : {'$not' : {'$begin' : prefix}}} //Field not begins with val - $begin String starts with prefix - {'fpath' : {'$begin' : prefix}} - $gt, $gte (>, >=) and $lt, $lte for number types: - {'fpath' : {'$gt' : number}, ...} - $bt Between for number types: - {'fpath' : {'$bt' : [num1, num2]}} - $in String OR Number OR Array val matches to value in specified array: - {'fpath' : {'$in' : [val1, val2, val3]}} - $nin - Not IN - $strand String tokens OR String array val matches all tokens in specified array: - {'fpath' : {'$strand' : [val1, val2, val3]}} - $stror String tokens OR String array val matches any token in specified array: - {'fpath' : {'$stror' : [val1, val2, val3]}} - $exists Field existence matching: - {'fpath' : {'$exists' : true|false}} - $icase Case insensitive string matching: - {'fpath' : {'$icase' : 'val1'}} //icase matching icase matching with '$in' operation: - {'name' : {'$icase' : {'$in' : ['HEllo', 'heLLo WorlD']}}} For case insensitive matching you can create special type of string index. - $elemMatch The $elemMatch operator matches more than one component within an array element. - { array: { $elemMatch: { value1 : 1, value2 : { $gt: 1 } } } } Restriction: only one $elemMatch allowed in context of one array field.
Queries can be used to update records:
$set Field set operation.
- {.., '$set' : {'field1' : val1, 'fieldN' : valN}}
$upsert Atomic upsert. If matching records are found it will be '$set' operation,
otherwise new record will be inserted with fields specified by argment object. - {.., '$upsert' : {'field1' : val1, 'fieldN' : valN}}
$inc Increment operation. Only number types are supported.
- {.., '$inc' : {'field1' : number, ..., 'field1' : number}
$dropall In-place record removal operation.
- {.., '$dropall' : true}
$addToSet Atomically adds value to the array only if its not in the array already.
If containing array is missing it will be created. - {.., '$addToSet' : {'fpath' : val1, 'fpathN' : valN, ...}}
$addToSetAll Batch version if $addToSet
- {.., '$addToSetAll' : {'fpath' : [array of values to add], ...}}
$pull Atomically removes all occurrences of value from field, if field is an array.
- {.., '$pull' : {'fpath' : val1, 'fpathN' : valN, ...}}
$pullAll Batch version of $pull
- {.., '$pullAll' : {'fpath' : [array of values to remove], ...}}
Collection joins supported in the following form:
{..., $do : {fpath : {$join : 'collectionname'}} } Where 'fpath' value points to object's OIDs from 'collectionname'. Its value can be OID, string representation of OID or array of this pointers.
NOTE: It is better to execute update queries with
$onlycount=true
hint flagor use the special `update()` method to avoid unnecessarily data fetching.
NOTE: Negate operations: $not and $nin not using indexes
so they can be slow in comparison to other matching operations.
NOTE: Only one index can be used in search query operation.
NOTE: If callback is not provided this function will be synchronous.
QUERY HINTS specified by calling Q:Skip Q:Max, Q:OrderBy, Q:Fields:
- $max Maximum number in the result set - $skip Number of skipped results in the result set - $orderby Sorting order of query fields. - $fields Set subset of fetched fields. If field presented in $orderby clause it will be forced to include in resulting records. Example: hints: { "$orderby" : { //ORDER BY field1 ASC, field2 DESC "field1" : 1, "field2" : -1 }, "$fields" : { //SELECT ONLY {_id, field1, field2} "field1" : 1, "field2" : 1 } }
To traverse selected records cursor object is returned. Cursor (res):
#res - length of result set res[i] - BSON representations of object as lua string res:object(i) - Lua table constructed from BSON data res:field(i, <field name>) - Lua value of fetched BSON object res() - Creates iterator for pairs (obj, idx) where obj - Lua table constructed from BSON data idx - Index of fetched object in the result set
Examples:
for i = 1, #res do local ob = res:object(i) ... end
OR
for i = 1, #res do res:field(i, "json field name") ... end
OR
for vobj, idx in res() do -- vobj is a lua table representation of fetched json object vobj["json field name"] ... end
Parameters:
- cname string Collection name
- q Q JSON query object
- flags
string
Query control flags:
`c`: only count of matching records will be returned without placing records in result set. `l`: return query execution log
Returns:
-
RS
result set, it will be
nil
ifc
flag presented in the controlflags
- number Count of matched/updated records
-
optional string
Query execution log if
l
flag presented in the controlflags
see also:
Usage:
db:find("mycoll", Q("foo", "bar")) => {"foo" : "bar"}
db:find("mycoll", Q("foo", "bar"):Max(10)) -- Limit results up to 10 records
db:find("parrots2", Q("likes", "toys"):OrderBy("name asc", "age desc"))
db:find("parrots2", Q():F("likes"):Eq("toys"):OrderBy({ name = 1 }, { age = -1 }))
- DB:findOne (cname, q)
-
Same as DB:find but retrieves only first matching JSON object.
Parameters:
Returns:
- DB:update (cname, q)
-
Convenient method to execute update queries.
Parameters:
Returns:
- number Count of matched/updated records
-
optional string
Query execution log if
l
flag presented in the controlflags
- DB:count (cname, q)
-
Convenient
count(*)
operation.Parameters:
Returns:
- number Count of matched/updated records
-
optional string
Query execution log if
l
flag presented in the controlflags
- DB:sync (cname)
-
Synchronize EJDB database with storage.
If
cname
is provided only this collection will be synced.Parameters:
- cname optional string Collection name
- DB:getDBMeta ()
-
Get table object describes a database structure and its collections.
Sample meta:
collections = { ecoll = { file = "testdb_ecoll", indexes = {}, name = "ecoll", options = { buckets = 425977, cachedrecords = 0, compressed = false, large = true }, records = 1 }, mycoll = { file = "testdb_mycoll", indexes = { { field = "foo", file = "testdb_mycoll.idx.sfoo.lex", iname = "sfoo", records = 3, type = "lexical" } }, name = "mycoll", options = { buckets = 131071, cachedrecords = 0, compressed = false, large = false }, records = 4 } }, file = "testdb"
Returns:
-
table
Database metadata
- DB:beginTransaction (cname)
-
Begin collection transaction.
Parameters:
- cname string Collection name
- DB:commitTransaction (cname)
-
Commit collection transaction.
Parameters:
- cname string Collection name
- DB:rollbackTransaction (cname)
-
Rollback collection transaction.
Parameters:
- cname string Collection name
- DB:getTransactionStatus (cname)
-
Get collection transaction status.
Returns
True
if transaction is active.Parameters:
- cname string Collection name
Returns:
-
bool
- DB:dropIndexes (cname, fpath)
-
DROP indexes of all types for JSON field path.
Parameters:
- DB:optimizeIndexes (cname, fpath)
-
OPTIMIZE indexes of all types for JSON field path.
Performs B+ tree index file optimization.
Parameters:
- DB:ensureStringIndex (cname, fpath)
-
Ensure index presence of String type for JSON field path.
Parameters:
- DB:rebuildStringIndex (cname, fpath)
-
Rebuild index of String type for JSON field path.
Parameters:
- DB:dropStringIndex (cname, fpath)
-
Drop index of String type for JSON field path.
Parameters:
- DB:ensureIStringIndex (cname, fpath)
-
Ensure case insensitive String index for JSON field path.
Parameters:
- DB:rebuildIStringIndex (cname, fpath)
-
Rebuild case insensitive String index for JSON field path.
Parameters:
- DB:dropIStringIndex (cname, fpath)
-
Drop case insensitive String index for JSON field path.
Parameters:
- DB:ensureNumberIndex (cname, fpath)
-
Ensure index presence of Number type for JSON field path.
Parameters:
- DB:rebuildNumberIndex (cname, fpath)
-
Rebuild index of Number type for JSON field path.
Parameters:
- DB:dropNumberIndex (cname, fpath)
-
Drop index of Number type for JSON field path.
Parameters:
- DB:ensureArrayIndex (cname, fpath)
-
Ensure index presence of Array type for JSON field path.
Parameters:
- DB:rebuildArrayIndex (cname, fpath)
-
Rebuild index of Array type for JSON field path.
Parameters:
- DB:rebuildArrayIndex (cname, fpath)
-
Drop index of Array type for JSON field path.
Parameters:
- RS:object (i)
-
Returns result set lua table object at specified position
i
Parameters:
- i number Position of record in the result set
Returns:
-
table
Resulting lua object constructed from BSON record.
- RS:field (i, name)
-
Returns field value of lua object at specified position
i
Parameters:
- i number Position of record in the result set
- name string JSON field name
Returns:
-
Value of field
- RS.__len ()
- Length of result set.
- Q:KV (key, value)
-
Adds field into current JSON object.
Parameters:
- key
- value
Usage:
Q():KV("foo", "bar"):KV("age", 30) => {"foo" : "bar", "age" : 30}
- Q:F (fname)
-
Set current field for the next operation during query building.
Parameters:
- fname string JSON field path
Usage:
Q:F("name"):Eq("andy"):F("age"):Gt(30) => {"name" : "andy", "age" : {"$gt" : 30}}
- Q:Eq (val)
-
Field equality restriction.
All usage samples represent same thing:
{"fname" : fval}
Parameters:
- val any BSON value as Lua object including Q instances.
Returns:
-
Self Q
Usage:
Q():F("fname"):Eq(fval)
Q("fname", fval)
Q():F("fname", fval)
- Q:ElemMatch (val)
-
Element match construction.
- $elemMatch The $elemMatch operator matches more than one component within an array element.
- { array: { $elemMatch: { value1 : 1, value2 : { $gt: 1 } } } }
Restriction: only one $elemMatch allowed in context of one array field.
Parameters:
- val
Returns:
-
Self Q
- Q:Not (val)
-
The $not negatiation for
val
blockParameters:
- val
Returns:
-
Self Q
Usage:
Q():Not(Q("foo", "bar")) => {"$not" : {"foo" : "bar"}}
- Q:Gt (val)
-
Greater than (val > arg)
Parameters:
- val number
Returns:
-
Self Q
Usage:
Q():F("age"):Gt(29) => {"age" : {"$gt" : 29}}
- Q:Gte (val)
-
Greater than or equal (val >= arg)
Parameters:
- val number
Returns:
-
Self Q
Usage:
Q():F("age"):Gt(29) => {"age" : {"$gte" : 29}}
- Q:Lt (val)
-
Lesser than (val < arg)
Parameters:
- val number
Returns:
-
Self Q
Usage:
Q():F("age"):Lt(29) => {"age" : {"$lt" : 29}}
- Q:Lte (val)
-
Lesser than or equal (val <= arg)
Parameters:
- val number
Returns:
-
Self Q
Usage:
Q():F("age"):Lt(29) => {"age" : {"$lte" : 29}}
- Q:Icase (val)
-
Case insensitive string matching
Parameters:
Returns:
-
Self Q
Usage:
Q():F("name"):Icase("aNdY") => {"name" : {"$icase" : "aNdY"}}
Q():F("name"):Icase({[$in] = {"aNdY", "AnTon"}}) => {"name" : {"$icase" : {"$in" : ["aNdY", "AnTon"]}}}
- Q:Begin (val)
-
String starts with prefix
Parameters:
- val string
Returns:
-
Self Q
Usage:
Q():F("fpath"):Begin("prefix") => {"fpath" : {"$begin" : "prefix"}}
- Q:In (val)
-
Field value matched any value of specified in
val
table.Parameters:
- val table Not empty lua array of values.
Returns:
-
Self Q
Usage:
Q():F("fpath"):In({"val1", "val2", "val3"}) => {"fpath" : {"$in" : ["val1", "val2", "val3"]}}
- Q:NotIn (val)
-
Negation of Q:In
Parameters:
- val
Returns:
-
Self Q
see also:
- Q:Bt (n1, n2)
-
Between for number types
Parameters:
- n1 number
- n2 number
Returns:
-
Self Q
Usage:
Q():F("age"):Bt(10, 20) => {"age" : {"$bt" : [10, 20]}}
- Q:StrAnd (val)
-
String tokens(or string array vals) matches all tokens in specified
val
array.Parameters:
- val table Array of tokens to match.
Returns:
-
Self Q
Usage:
Q():F("description"):StrAnd({"foo", "bar"}) -- descripton contains all tokens: 'foo' and 'bar'
- Q:StrOr (val)
-
String tokens(or string array vals) matches any token in specified array.
Parameters:
- val table Array of tokens to match.
Returns:
-
Self Q
Usage:
Q():F("description"):StrOr({"foo", "bar"}) -- descripton contains all tokens: 'foo' or 'bar'
- Q:Inc (val)
-
Increment current field. Only number types are supported.
Parameters:
- val number
Returns:
-
Self Q
see also:
Usage:
Q():F("count"):Inc(1):F("age"):Inc(-20) => {"$inc" : {"count" : 1, "age" : -20}}
- Q:Set (val)
-
Set fields to values.
Parameters:
Returns:
-
Self Q
Usage:
Q():Set({age = 20, count = 1}) => {"$set" : {"age" : 20, count : 1}}
- Q:Upsert (val)
-
Atomic upsert.
If matching records are found it will be
$set
operation, otherwise new record will be inserted with fields specified byval
table.Parameters:
Returns:
-
Self Q
Usage:
Q("foo","bar"):Upsert(Q("foo", "bar")) => {"foo" : "bar", "$upsert" : {"foo" : "bar"}}
Q("foo","bar"):Upsert({foo ="bar"}) => {"foo" : "bar", "$upsert" : {"foo" : "bar"}}
- Q:AddToSet (val)
-
Atomically adds
val
to thearray field
only ifval
not in the array already. If containing array is missing it will be created.Parameters:
- val Value to add
Returns:
-
Self Q
Usage:
Q():F("tags"):AddToSet("red") => {"$addToSet" : {"tags" : "red"}}
- Q:AddToSetAll (val)
-
Atomically performs
set union
with values inval
for specified array field.Parameters:
- val table Array of values to add
Returns:
-
Self Q
see also:
Usage:
Q():F("tags"):AddToSetAll({"red", "green"})
- Q:Pull (val)
-
Atomically removes all occurrences of
val
from field, if field is an array.Parameters:
- val Value to remove
Returns:
-
Self Q
see also:
Usage:
Q():F("tags"):Pull("red") => {"$pull" : {"tags" : "red"}}
- Q:PullAll (val)
-
Atomically performs
set substraction
of values inval
for specified array field.Parameters:
- val table Array of values to remove from array field
Returns:
-
Self Q
see also:
Usage:
Q():F("tags"):PullAll({"red", "green"}) => {"$pullAll" : {"tags" : ["red", "green"]}}
- Q:DropAll ()
-
In-place record removal operation.
Returns:
-
Self Q
Usage:
db:update(Q():F("name", "andy"):DropAll()) -- Removes all records with name eq 'andy'
- Q:Join (cname, fpath)
-
Make collection join
for select queries.
Parameters:
Returns:
-
Self Q
- Q:Or (...)
-
Add OR joined query restrictions.
Parameters:
Returns:
-
Self Q
Usage:
Q():Or(Q("name", "anton"), Q("name", "andy")) Find records with "name" field eq "anton" or "andy"
- Q:Skip (val)
-
Sets number of skipped records in the result set.
Parameters:
- val number
Returns:
-
Self Q
- Q:Max (val)
-
Sets max number of records in the result set.
Parameters:
- val number
Returns:
-
Self Q
- Q:OrderBy (...)
-
Set sorting rules for query results.
tparam table|string
Parameters:
- ...
Usage:
Q:OrderBy("name asc", "age desc") => ORDER BY name ASC, age dESC
Q:OrderBy({name = 1}, {age = -1}) => ORDER BY name ASC, age dESC
- Q:Fields (...)
-
Sets fields to be included in resulting objects.
If field presented in $orderby clause it will be forced to include in resulting records.
Parameters:
- ... string Fields to be included in fetched objects.
Returns:
-
Self Q
Usage:
Q:Fields("name", "age")
- Q:NotFields (...)
-
Sets fields to be excluded from resulting objects.
Parameters:
- ... string Fields to be excluded from fetched objects.
Returns:
-
Self Q
Usage:
Q:NotFields("name", "description")
Tables
- Q
-
Query/JSON builder is used to create EJDB queries or JSON objects with
preserverd keys order (Unlike lua tables).
Q can be used to construct BSON objects as well as queries.
Examples:
see also:
- Q:KV
- Q:F
- Q:Eq
- Q:ElemMatch
- Q:Not
- Q:Gt
- Q:Gte
- Q:Lt
- Q:Lte
- Q:Icase
- Q:Begin
- Q:In
- Q:NotIn
- Q:Bt
- Q:StrAnd
- Q:StrOr
- Q:Inc
- Q:Set
- Q:AddToSet
- Q:AddToSetAll
- Q:Pull
- Q:PullAll
- Q:Upsert
- Q:Upsert
- Q:DropAll
- Q:Join
- Q:Or
- Q:Skip
- Q:Skip
- Q:Max
- Q:OrderBy
- Q:Fields
- Q:Fields
- Q:NotFields
Usage:
Q("foo", "bar")
Q("likes", "toys"):OrderBy("name asc", "age desc")
Q("name", "Andy"):F("_id"):Eq("510f7fa91ad6270a00000000"):F("age"):Gt(20):Lt(40):F("score"):In({ 11, 22.12333, 1362835380447, db.toNull() }):Max(232)
Q():Or(Q("foo", "bar"), Q("foo", "bar6")):OrderBy({ foo = 1 })
- DB
- Database itself.
- RS
-
Result set cursor object. Usage:
#res - length of result set res[i] - BSON representations of object as lua string res:object(i) - Lua table constructed from BSON data res:field(i, <field name>) - Lua value of fetched BSON object res() - Creates iterator for pairs (obj, idx) where obj - Lua table constructed from BSON data idx - Index of fetched object in the result set
Examples:
for i = 1, #res do local ob = res:object(i) ... end
OR
for i = 1, #res do res:field(i, "json field name") ... end
OR
for vobj, idx in res() do -- vobj is a lua table representation of fetched json object vobj["json field name"] ... end
see also: