mirror of
https://github.com/cloudwu/skynet.git
synced 2026-07-24 12:20:41 +00:00
add mongo.createIndexs, and fix the bug in old API createIndex. For detail, see PR #511
This commit is contained in:
@@ -318,30 +318,63 @@ function mongo_cursor:count(with_limit_and_skip)
|
||||
end
|
||||
|
||||
|
||||
-- For compatibility.
|
||||
-- collection:createIndex({username = 1}, {unique = true})
|
||||
function mongo_collection:createIndex(keys, option)
|
||||
local name = option.name
|
||||
option.name = nil
|
||||
|
||||
if not name then
|
||||
for k, v in pairs(keys) do
|
||||
name = (name == nil) and k or (name .. "_" .. k)
|
||||
name = name .. "_" .. v
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
local doc = {};
|
||||
doc.name = name
|
||||
doc.key = keys
|
||||
for k, v in pairs(option) do
|
||||
local function createIndex_onekey(self, key, option)
|
||||
local doc = {}
|
||||
for k,v in pairs(option) do
|
||||
doc[k] = v
|
||||
end
|
||||
local k,v = next(key) -- support only one key
|
||||
doc.name = doc.name or (k .. "_" .. v)
|
||||
doc.key = key
|
||||
|
||||
return self.database:runCommand("createIndexes", self.name, "indexes", {doc})
|
||||
end
|
||||
|
||||
mongo_collection.ensureIndex = mongo_collection.createIndex;
|
||||
|
||||
local function IndexModel(option)
|
||||
local doc = {}
|
||||
for k,v in pairs(option) do
|
||||
if type(k) == "string" then
|
||||
doc[k] = v
|
||||
end
|
||||
end
|
||||
|
||||
local keys = {}
|
||||
local name
|
||||
for _, kv in ipairs(option) do
|
||||
local k,v = next(kv)
|
||||
table.insert(keys, k)
|
||||
table.insert(keys, v)
|
||||
name = (name == nil) and k or (name .. "_" .. k)
|
||||
name = name .. "_" .. v
|
||||
end
|
||||
|
||||
doc.name = doc.name or name
|
||||
doc.key = bson_encode_order(table.unpack(keys))
|
||||
|
||||
return doc
|
||||
end
|
||||
|
||||
-- collection:createIndex { { key1 = 1}, { key2 = 1 }, unique = true }
|
||||
function mongo_collection:createIndex(option , onekey)
|
||||
if onekey then
|
||||
return createIndex_onekey(self, option, onekey)
|
||||
end
|
||||
|
||||
return self.database:runCommand("createIndexes", self.name, "indexes", { IndexModel(option) })
|
||||
end
|
||||
|
||||
function mongo_collection:createIndexs(...)
|
||||
local idx = { ... }
|
||||
for k,v in ipairs(idx) do
|
||||
idx[k] = IndexModel(v)
|
||||
end
|
||||
return self.database:runCommand("createIndexes", self.name, "indexes", idx)
|
||||
end
|
||||
|
||||
mongo_collection.ensureIndex = mongo_collection.createIndex
|
||||
|
||||
function mongo_collection:drop()
|
||||
return self.database:runCommand("drop", self.name)
|
||||
|
||||
Reference in New Issue
Block a user