- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我有一个非常简单的$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.
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
$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
操作中完成的,除了匹配的结果外,没有其他实际结果会返回。
$group
,则将结果返回到数组格式,一旦它们被实际执行的“隐藏查询”有效地过滤掉了通过
$lookup
。
$unwind
的原因。但是,存在一个局限性,即由于“
$unwind
”,“LEFT JOIN”变成了“INNER JOIN”,因此无法保留内容。同样,即使
preserveNulAndEmptyArrays
也会否定“凝聚”并仍然保留完整的数组,从而导致相同的BSON限制问题。
$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
的正常行为而没有任何其他选择。
$unwind
来实现“INNER JOIN”。
关于mongodb - 总计$ lookup匹配管道中文档的总大小超过了最大文档大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45724785/
我需要一些帮助。 我希望“总计”由“数量*价格=总计”计算(到目前为止没问题)。问题是我还需要通过“总/价格=数量”来计算“数量”,即如果一个字段发生更改,另一个字段也会自动更改。 我做了一个非常简单
我的项目即将结束,但在解决它时遇到了一些问题。我是一名厨师,想要自己的应用程序与他自己的业务相关 我的表单称为“菜谱”,并包含数量、单价、使用百分比。 假设您有 1 公斤苹果,价格为 5 欧元。清洁结
我的数据库表是: 产品展示 - ID - 名称 ... 订单 - ID - 状态 ... OrderItems - ID -order_id -product_id -数量 -line_total 我
我的项目即将结束,但在解决它时遇到了一些问题。我是一名厨师,想要自己的应用程序与他自己的业务相关 我的表单称为“菜谱”,并包含数量、单价、使用百分比。 假设您有 1 公斤苹果,价格为 5 欧元。清洁结
exchanges表结构: id exchange created_at updated_at deleted_at start_time
我正在开发 Telerik RadGrid,网格内有多个 radtextbox,如 A、B、C 和 D。我使用带有正则表达式验证的 radtextbox 来验证带有数字的 A、B 和 C 文本框。然而
我有一个非常简单的$lookup聚合查询,如下所示: {'$lookup': {'from': 'edge', 'localField': 'gid', 'foreignField': 't
我正在尝试做一些与我之前问过的问题非常相似的事情,但我似乎无法让它正常工作。这是我之前的问题:How to get totals per day 表格如下: Table N
[更新] 谢谢大家,最终代码: var EUR_share_cost = 0; var USD_share_cost = 0; var GBP_shar
由于某种原因,下面的这部分代码没有将每个数组项添加到一起。我单步执行调试器,正在创建并递增数组项,但 total += ScoreArray[i]; 似乎没有将已输入的数字相加。相反,我只是将第一个输
我在这里有点迷路了。我有一个 for 循环,它增加一个值,如下所示: int nu01 = 10000; int level = 0; int increase = 35000; for (int i
请引用之前的问题:Sum total for column in jQuery 我使用了 Aymen 的解决方案,但我对其进行了编辑以满足我的需要。它停止工作,我的代码如下所示,在 jsfiddle
Date Flight ID Member ID Seat Type Seat Price 2013-07-28 F71498 M692
我希望程序忽略零总数。我正试图阻止向非参与者提供零总数的汽车奖励。我在 && 运算符后面添加了 >= 表达式。这对于击杀数和净值来说正确吗? $fetch_nor_killers = mysq
我有下表: CREATE TABLE zoom (`id` int, `fb_id` int, `date` datetime); INSERT INTO zoom (`id`, `f
我想知道是否有一种方法可以将已计算的派生列的总和添加到新列中。 Employee_KT_State --------------------------------------------------
在 SQL 中,我想获得来自每个用户的网站点击率的百分比。为此,我需要获取 site hits 列的总和,但我的查询在另一列上使用了 GROUP By。 除了 GROUP BY 中的每个 user_i
我有以下查询: SELECT SUM(case when s1 = 'fel' then 1 else 0 end) as s1_count, SUM(case when s2 = '
我已经使用 HTML 创建了一个表格。该表由一个标题和许多称为 Family 的行组成。每个家庭行可以有许多行代表家庭的各个成员(请参见下面的代码)。 Family N
如何使用 javascript 给出 float 总计。请 friend 们帮助我。 function addNumbers() {
我是一名优秀的程序员,十分优秀!