From fe9640e2dd6224b1f7257b08e806a5db3e019b5c Mon Sep 17 00:00:00 2001 From: dpull Date: Thu, 4 Dec 2014 20:10:24 +0800 Subject: [PATCH] =?UTF-8?q?1=E3=80=81mongo=5Fcollection:createIndex=20?= =?UTF-8?q?=E5=88=9B=E5=BB=BA=E7=B4=A2=E5=BC=95=202=E3=80=81mongo=5Fcollec?= =?UTF-8?q?tion:safe=5Finsert=20=E5=8F=AF=E4=BB=A5=E5=88=A4=E6=96=AD?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E5=80=BC=E7=9A=84insert=203=E3=80=81mongo=5F?= =?UTF-8?q?collection:findAndModify=20=E6=9F=A5=E8=AF=A2=E5=B9=B6=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lualib/mongo.lua | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) 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