gpt4 book ai didi

node.js - MongoDB 性能问题,可能是由于使用 native MongoDB 驱动程序在 NodeJS 项目中忽略了投影

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:42 24 4
gpt4 key购买 nike

长版本:(向下滚动查看 TLDR)

我有一个收藏“图书馆”。库可以是"template"或“标准模板”类型(在这种情况下)。如果它由组织拥有,它将包含一个“organization_id”(否则为空),如果它是无主的,但组织可以访问它,则该 id 将被添加到“organizations”数组中。类型为"template"的库始终被拥有,而类型为“标准模板”的库永远不会被拥有。执行此操作的查询如下所示:

{
"$or": [{
"organization_id": id,
"type": "template"
}, {
"organization_id": null,
"type": "standard-template",
"organizations": id
}]
}

我有一个像 {"organization_id": 1, "type": 1} 这样的索引,并且没有很多“标准模板”库。解释会告诉我这个查询需要 +- 4ms 来执行并返回 50 个文档。

在我的 NodeJS 应用程序中,大约需要 12 秒。这可能是由于每个文档的大小(可能从几 KB 到 10MB 不等)造成的。

我试图使用投影来限制它仅接收相关字段,但是,这似乎被完全忽略。我尝试了下面代码的各种变体,但似乎都没有什么区别。

TLDR

我的代码中的投影值似乎被忽略了。在示例中,我尝试仅检索“_id”字段,但最终得到整个文档。

用于测试的代码

let id = ObjectID('5e56503cafc87b893b92827c');
let start = performance.now();
let find = mongodb.collection('libraries').find(
{
"$or": [
{"organization_id": id, "type": "template"},
{"organization_id": null,"type": "standard-template", "organizations": id}
]
}, {_id: 1});

while (await find.hasNext()) {
const doc = await find.next();
console.log(doc); //HUGE! way more than just _id!
}

console.log(performance.now() - start); //about 12000 ms

更短的测试代码:

console.log(await mongodb.collection('libraries').findOne({}, {_id: 1})); //HUGE!

在任何示例或文档中,我发现它的完成方式似乎都是相同的。我很确定我过去也这样做过。我在监督什么吗?非常感谢任何见解。

最佳答案

由于您使用游标来遍历记录,因此需要链接项目函数来应用投影。你所做的方式忽略了投影。您的代码应该如下所示

et id = ObjectID('5e56503cafc87b893b92827c');
let start = performance.now();
let find = mongodb.collection('libraries').find(
{
"$or": [
{"organization_id": id, "type": "template"},
{"organization_id": null,"type": "standard-template", "organizations": id}
]
}).project({_id: 1}); // this is the projection

while (await find.hasNext()) {
const doc = await find.next();
console.log(doc); //HUGE! way more than just _id!
}

console.log(performance.now() - start); //about 12000 ms

或者

您可以将投影包装在像这样的投影属性中

{"projection": {"_id": 1}}

这两者都应该有效。

关于node.js - MongoDB 性能问题,可能是由于使用 native MongoDB 驱动程序在 NodeJS 项目中忽略了投影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60465090/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com