即使使用 allowDiskUse true 选项也会出现 BSONObj 大小错误

Getting BSONObj size error even with allowDiskUse true option

我有一个包含 3 亿个文档的集合,每个文档都有一个 user_id 字段,如下所示:

{
    "user_id": "1234567",
    // and other fields
}

我想要集合中唯一 user_ids 的列表,但以下 mongo shell 命令会导致错误。

db.collection.aggregate([
  { $group: { _id: null, user_ids: { $addToSet: "$user_id" } } }
], { allowDiskUse: true });
2021-11-23T14:50:28.163+0900 E  QUERY    [js] uncaught exception: Error: command failed: {
        "ok" : 0,
        "errmsg" : "Error on remote shard <host>:<port> :: caused by :: BSONObj size: 46032166 (0x2BE6526) is invalid. Size must be between 0 and 16793600(16MB) First element: _id: null",
        "code" : 10334,
        "codeName" : "BSONObjectTooLarge",
        "operationTime" : Timestamp(1637646628, 64),
        ...
} : aggregate failed :

为什么即使使用allowDiskUse: true 选项也会出现错误? 数据库版本 4.2.16.

distinct 可能更有用

db.collection.distinct( "user_id" )

您尝试在单个文档中插入所有唯一 user_ids,但显然该文档的大小变得大于 16MB 导致了问题。