diff --git a/lualib/skynet/db/mongo.lua b/lualib/skynet/db/mongo.lua index fd9e2c0c..0eb14e8f 100644 --- a/lualib/skynet/db/mongo.lua +++ b/lualib/skynet/db/mongo.lua @@ -365,6 +365,18 @@ function mongo_collection:batch_insert(docs) sock:request(pack) end +function mongo_collection:safe_batch_insert(docs) + for i = 1, #docs do + if docs[i]._id == nil then + docs[i]._id = bson.objectid() + end + docs[i] = bson_encode(docs[i]) + end + + local r = self.database:runCommand("insert", self.name, "documents", docs) + return werror(r) +end + function mongo_collection:update(selector,update,upsert,multi) local flags = (upsert and 1 or 0) + (multi and 2 or 0) local sock = self.connection.__sock diff --git a/test/testmongodb.lua b/test/testmongodb.lua index 54d5c265..0a102942 100644 --- a/test/testmongodb.lua +++ b/test/testmongodb.lua @@ -168,6 +168,24 @@ function test_expire_index() assert(false, "test expire index failed"); end +local function test_safe_batch_insert() + local ok, err, ret + local c = _create_client() + local db = c[db_name] + + db.testcoll:drop() + + local docs, length = {}, 10 + for i = 1, length do + table.insert(docs, {test_key = i}) + end + + db.testcoll:safe_batch_insert(docs) + + local ret = db.testcoll:find() + assert(length == ret:count(), "test safe batch insert failed") +end + skynet.start(function() if username then print("Test auth") @@ -183,5 +201,7 @@ skynet.start(function() test_runcommand() print("Test expire index") test_expire_index() + print("test safe batch insert") + test_safe_batch_insert() print("mongodb test finish."); end)