diff --git a/lualib/mongo.lua b/lualib/mongo.lua index 458e1a6c..38ac20dd 100644 --- a/lualib/mongo.lua +++ b/lualib/mongo.lua @@ -227,7 +227,11 @@ function mongo_collection:insert(doc) sock:request(pack) end -function mongo_collection:batch_insert(docs) +function mongo_collection:safe_insert(doc) + return self.database:runCommand("insert", self.name, "documents", {bson_encode(doc)}) +end + +function mongo_collection:batch_insert(docs) for i=1,#docs do if docs[i]._id == nil then docs[i]._id = bson.objectid() @@ -276,6 +280,48 @@ function mongo_collection:find(query, selector) } , cursor_meta) end +-- collection:createIndex({username = 1}, {unique = true}) +function mongo_collection:createIndex(keys, option) + local name + for k, v in pairs(keys) do + assert(v == 1) + name = (name == nil) and k or (name .. "_" .. k) + end + + local doc = {}; + doc.name = name + doc.key = keys + for k, v in pairs(option) do + if v then + doc[k] = true + end + end + return self.database:runCommand("createIndexes", self.name, "indexes", {doc}) +end + +mongo_collection.ensureIndex = mongo_collection.createIndex; + +-- collection:findAndModify({query = {name = "userid"}, update = {["$inc"] = {nextid = 1}}, }) +-- keys, value type +-- query, table +-- sort, table +-- remove, bool +-- update, table +-- new, bool +-- fields, bool +-- upsert, boolean +function mongo_collection:findAndModify(doc) + assert(doc.query) + assert(doc.update or doc.remove) + + local cmd = {"findAndModify", self.name}; + for k, v in pairs(doc) do + table.insert(cmd, k) + table.insert(cmd, v) + end + return self.database:runCommand(unpack(cmd)) +end + function mongo_cursor:hasNext() if self.__ptr == nil then if self.__document == nil then