mongodb - 总计$ lookup匹配管道中文档的总大小超过了最大文档大小

标签 mongodb aggregation-framework

我有一个非常简单的$lookup聚合查询,如下所示:

{'$lookup':
 {'from': 'edge',
  'localField': 'gid',
  'foreignField': 'to',
  'as': 'from'}}

当我在具有足够文档的匹配项上运行此命令时,出现以下错误:
Command failed with error 4568: 'Total size of documents in edge
matching { $match: { $and: [ { from: { $eq: "geneDatabase:hugo" }
}, {} ] } } exceeds maximum document size' on server

所有限制文档数量的尝试均失败。 allowDiskUse: true不执行任何操作。发送cursor不会执行任何操作。在聚合中添加$limit也会失败。

怎么会这样

然后,我再次看到错误。该$match$and$eq来自何处?幕后的聚合管道是否将$lookup调用移植到另一种聚合,它是独立运行的,我无法为游标提供限制或使用游标?

这里发生了什么?

最佳答案

如前面的注释中所述,发生错误是因为执行 $lookup 默认情况下根据外部集合的结果在父文档中生成目标“数组”时,为该数组选择的文档总大小会导致父文档超过16MB BSON Limit.
此操作的计数器将使用 $unwind 进行处理,它立即跟随 $lookup 管道阶段。实际上,这会更改 $lookup 的行为,从而代替在父级中生成数组,结果是为每个匹配的文档为每个父级提供“副本”。
类似于 $unwind 的常规用法,不同的是unwinding操作实际上被添加到 $lookup 管道操作本身中,而不是作为“单独的”管道阶段进行处理。理想情况下,您还应在 $unwind 后面加上 $match 条件,这还会创建一个matching参数,也要添加到 $lookup 中。您实际上可以在管道的explain输出中看到这一点。
核心文档的Aggregation Pipeline Optimization部分实际上(简要地)涵盖了该主题:

$lookup + $unwind Coalescence

New in version 3.2.

When a $unwind immediately follows another $lookup, and the $unwind operates on the as field of the $lookup, the optimizer can coalesce the $unwind into the $lookup stage. This avoids creating large intermediate documents.


最好的证明是 list ,通过创建超过16MB BSON限制的“相关”文档,使服务器承受压力。尽可能简短地打破和解决BSON限制:
const MongoClient = require('mongodb').MongoClient;

const uri = 'mongodb://localhost/test';

function data(data) {
  console.log(JSON.stringify(data, undefined, 2))
}

(async function() {

  let db;

  try {
    db = await MongoClient.connect(uri);

    console.log('Cleaning....');
    // Clean data
    await Promise.all(
      ["source","edge"].map(c => db.collection(c).remove() )
    );

    console.log('Inserting...')

    await db.collection('edge').insertMany(
      Array(1000).fill(1).map((e,i) => ({ _id: i+1, gid: 1 }))
    );
    await db.collection('source').insert({ _id: 1 })

    console.log('Fattening up....');
    await db.collection('edge').updateMany(
      {},
      { $set: { data: "x".repeat(100000) } }
    );

    // The full pipeline. Failing test uses only the $lookup stage
    let pipeline = [
      { $lookup: {
        from: 'edge',
        localField: '_id',
        foreignField: 'gid',
        as: 'results'
      }},
      { $unwind: '$results' },
      { $match: { 'results._id': { $gte: 1, $lte: 5 } } },
      { $project: { 'results.data': 0 } },
      { $group: { _id: '$_id', results: { $push: '$results' } } }
    ];

    // List and iterate each test case
    let tests = [
      'Failing.. Size exceeded...',
      'Working.. Applied $unwind...',
      'Explain output...'
    ];

    for (let [idx, test] of Object.entries(tests)) {
      console.log(test);

      try {
        let currpipe = (( +idx === 0 ) ? pipeline.slice(0,1) : pipeline),
            options = (( +idx === tests.length-1 ) ? { explain: true } : {});

        await new Promise((end,error) => {
          let cursor = db.collection('source').aggregate(currpipe,options);
          for ( let [key, value] of Object.entries({ error, end, data }) )
            cursor.on(key,value);
        });
      } catch(e) {
        console.error(e);
      }

    }

  } catch(e) {
    console.error(e);
  } finally {
    db.close();
  }

})();
插入一些初始数据后, list 将尝试运行仅由 $lookup 组成的聚合,该聚合将因以下错误而失败:

{ MongoError: Total size of documents in edge matching pipeline { $match: { $and : [ { gid: { $eq: 1 } }, {} ] } } exceeds maximum document size


这基本上是在告诉您检索超出了BSON限制。
相比之下,下一次尝试将添加 $unwind $match 管道阶段
解释输出:
  {
    "$lookup": {
      "from": "edge",
      "as": "results",
      "localField": "_id",
      "foreignField": "gid",
      "unwinding": {                        // $unwind now is unwinding
        "preserveNullAndEmptyArrays": false
      },
      "matching": {                         // $match now is matching
        "$and": [                           // and actually executed against 
          {                                 // the foreign collection
            "_id": {
              "$gte": 1
            }
          },
          {
            "_id": {
              "$lte": 5
            }
          }
        ]
      }
    }
  },
  // $unwind and $match stages removed
  {
    "$project": {
      "results": {
        "data": false
      }
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "results": {
        "$push": "$results"
      }
    }
  }
而且该结果当然是成功的,因为由于不再将结果放入父文档中,因此不能超过BSON限制。
这仅是由于仅添加 $unwind 而发生的,但是例如添加 $match 表示这是,也是添加到 $lookup 阶段的结果,总体效果是“限制”以有效方式返回的结果,因为这些操作都是在 $lookup 操作中完成的,除了匹配的结果外,没有其他实际结果会返回。
通过这种方式构造,您可以查询超出BSON限制的“引用数据”,然后如果您想要 $group ,则将结果返回到数组格式,一旦它们被实际执行的“隐藏查询”有效地过滤掉了通过 $lookup

MongoDB 3.6及更高版本-“LEFT JOIN”的附加功能
如上述所有内容所述,BSON限制是您不能违反的“硬” 限制,通常这就是为什么在过渡步骤中需要 $unwind 的原因。但是,存在一个局限性,即由于“ $unwind ”,“LEFT JOIN”变成了“INNER JOIN”,因此无法保留内容。同样,即使preserveNulAndEmptyArrays也会否定“凝聚”并仍然保留完整的数组,从而导致相同的BSON限制问题。
MongoDB 3.6向 $lookup 添加了新语法,该语法允许使用“子管道”表达式代替“本地”和“外来”键。因此,除了使用所演示的“coalescence”选项之外,只要生成的数组也没有超出限制,就可以在返回数组“intact”的管道中放置条件,并且可能没有指示性的匹配项“左联接”。
新的表达式将是:
{ "$lookup": {
  "from": "edge",
  "let": { "gid": "$gid" },
  "pipeline": [
    { "$match": {
      "_id": { "$gte": 1, "$lte": 5 },
      "$expr": { "$eq": [ "$$gid", "$to" ] }
    }}          
  ],
  "as": "from"
}}
实际上,这基本上就是MongoDB使用以前的语法“在幕后”进行的工作,因为3.6“内部”使用 $expr 来构造语句。当然,区别在于在实际执行 "unwinding" 的方式上没有$lookup选项。
如果"pipeline"表达式没有实际生成任何文档,则主文档中的目标数组实际上将为空,就像“LEFT JOIN”实际上一样,并且是 $lookup 的正常行为而没有任何其他选择。
但是,的输出数组一定不能使创建该文档的文档超出BSON限制。因此,实际上取决于您的条件是确保任何“匹配”内容都保持在此限制之内,否则相同的错误将持续存在,除非您当然实际使用 $unwind 来实现“INNER JOIN”。

关于mongodb - 总计$ lookup匹配管道中文档的总大小超过了最大文档大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45724785/

相关文章:

mongodb - 如何使用 MongoDb id 数组获取多个文档?

javascript - Node、MongoDB 和 Promise 的问题

javascript - Meteor.js 和 Collection2 : Update Method that Inserts New Object in subschema

php - 使用 mongoDB Jenssegers Laravel 运行原始查询

$lookup 阶段内的 MongoDB 聚合 $elemMatch

javascript - 高效地向 MongoDB 结果添加额外字段

MongoDB 按日期以字符串格式聚合不起作用

mongodb - 在其他集合中查找值的计数

node.js - MongoDB 查询两个集合以添加/减去第一个集合中的字段与第二个集合中的匹配字段

javascript - 更新 mongodb 中的聚合结果?