MongoDB性能问题,可能是由于使用本机MongoDB驱动程序而在NodeJS项目中忽略了投影

问题描述 投票:0回答:1

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

我有一个集合“图书馆”。库可以是“模板”或“标准模板”类型(在这种情况下)。如果它是一个组织所拥有的,它将包含一个“ organization_id”(否则为null);如果它是不拥有的,但是一个组织可以访问它,则此ID将被添加到“组织”数组中。始终拥有“模板”类型的库,而从未拥有“标准模板”类型的库。这样做的查询看起来像:

{
    "$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!

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

node.js mongodb mongodb-query node-mongodb-native
1个回答
0
投票

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

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

OR

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

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

这两个都应该起作用。

© www.soinside.com 2019 - 2024. All rights reserved.