From c6a8976bc3adeb4213e2e0060cb4ac543c004544 Mon Sep 17 00:00:00 2001 From: Whislly Date: Mon, 10 Jul 2023 12:29:16 +0800 Subject: [PATCH] =?UTF-8?q?findOne=E4=BC=98=E5=8C=96=20(#1772)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1、直接调用runCommand方法 2、增加"limit": 1参数,限制只返回一条数据 --- lualib/skynet/db/mongo.lua | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lualib/skynet/db/mongo.lua b/lualib/skynet/db/mongo.lua index 51a9ee2d..325a68c9 100644 --- a/lualib/skynet/db/mongo.lua +++ b/lualib/skynet/db/mongo.lua @@ -494,11 +494,12 @@ function mongo_collection:raw_safe_delete(delete) end function mongo_collection:findOne(query, projection) - local cursor = self:find(query, projection) - if cursor:hasNext() then - return cursor:next() + local r = self.database:runCommand("find", self.name, "filter", query and bson_encode(query) or empty_bson, + "limit", 1, "projection", projection and bson_encode(projection) or empty_bson) + if r.ok ~= 1 then + error(r.errmsg or "Reply from mongod error") end - return nil + return r.cursor.firstBatch[1] end function mongo_collection:find(query, projection)