Mongolite Error: Failed to read 4 bytes: socket error or timeout

Mongolite Error: Failed to read 4 bytes: socket error or timeout

我试图在 mongo 数据库中查询数据库中包含的所有 ID,以便将列表与单独的数据框进行比较。但是,当我尝试查找所有 sample_id 字段时,我看到的是:

Error: Failed to read 4 bytes: socket error or timeout

查找查询示例:

library(mongolite)
mongo <- mongo(collection,url = paste0("mongodb://", user,":",pass, "@", mongo_host, ":", port,"/",db))
mongo$find(fields = '{"sample_id":1,"_id":0}')
# Error: Failed to read 4 bytes: socket error or timeout

如错误所示,这可能是由于数据量大导致的一些内部套接字超时问题。但是,在 the mongo documentation 中默认设置为从不超时。

socketTimeoutMS: The time in milliseconds to attempt a send or receive on a socket before the attempt times out. The default is never to timeout, though different drivers might vary. See the driver documentation.

所以我的问题是为什么在使用 mongolite 时会出现此错误?我想我已经解决了它,但我欢迎任何其他信息或意见。

简单的答案是,正如上面引自 mongo 文档中所指出的那样,"different drivers might vary"。在这种情况下,mongolite 的默认值是 5 分钟,在 this github 问题中发现,我猜它与 C 驱动程序有关。

The default socket timeout for connections is 5 minutes. This means that if your MongoDB server dies or becomes unavailable it will take 5 minutes to detect this. You can change this by providing sockettimeoutms= in your connection URI.

github 问题中还提到了一个解决方案,即增加 URI 中的 sockettimeoutms。在连接 URI 的末尾,您应该添加 ?sockettimeoutms=1200000 作为选项以增加套接字超时前的时间长度(在本例中为 20 分钟)。修改原示例代码:

library(mongolite)
mongo <- mongo(collection,url = paste0("mongodb://", user,":",pass, "@", mongo_host, ":", port,"/",db,"?sockettimeoutms=1200000"))
mongo$find(fields = '{"sample_id":1,"_id":0}')

Laravel:在您的 database.php 'sockettimeoutms' => '1200000' 中,添加这个并享受旅程