【发布时间】:2016-04-20 10:05:28
【问题描述】:
我有一个树状架构,它指定了一组父项和一组子项。
孩子的集合可能有数百万个文档 - 每个文档都包含少量数据,并且对它所属的父级的引用存储为字符串(可能是我的第一个错误)。
父母的集合要少得多,但可能仍然在数万之内,并且会随着时间的推移慢慢增长。不过一般来说,单亲父母可能有少至 10 个孩子,或多至 50,000 个(可能更多,但不太可能)。
单个子文档可能如下所示:
{
_id: ObjectId("507f191e810c19729de860ea"),
info: "Here's some info",
timestamp: 1234567890.0,
colour: "Orange",
sequence: 1000,
parent: "12a4567b909c7654d212e45f"
}
其对应的父记录(位于单独的集合中)可能如下所示:
{
_id: ObjectId("12a4567b909c7654d212e45f")
info: "Blah",
timestamp: 1234567890.0
}
我在 mongoose 中的查询(其中包含请求中的父 ID)如下所示:
/* GET all children with the specified parent ID */
module.exports.childrenFromParent = function(req, res) {
parentID = req.params.parentID;
childModel.find({
"parentid": parentID
}).sort({"sequence": "asc"}).exec(
function(err, children) {
if (!children) {
sendJSONResponse(res, 404, {
"message": "no children found"
});
return;
} else if (err) {
sendJSONResponse(res, 404, err);
return;
}
sendJSONResponse(res, 200, children);
}
);
};
所以基本上发生的事情是,查询必须在整个子集合中搜索任何具有与提供的 ID 匹配的父文档的文档。
我目前将此父 ID 作为字符串保存在子集合架构(上面代码中的 childModel)中,这可能是个坏主意,但是,我的 API 在请求中将父 ID 作为字符串提供。
如果有人对我如何修复架构或更改查询以提高性能有任何想法,我们将不胜感激!
【问题讨论】:
-
“父”字段有索引吗?
-
@risyasin 不,没有。
-
我建议您在父字段上创建一个索引以帮助加快查询速度。请参阅docs.mongodb.org/v3.0/core/indexes-introduction 了解更多信息。
-
您还可以使用
.explain("executionStats")分析索引的好处,参见:docs.mongodb.org/v3.0/tutorial/analyze-query-plan -
@AshleyB 感谢您提供的信息。您是否碰巧知道索引更改是否具有追溯性,还是仅适用于新插入的文档?
标签: node.js mongodb rest express mongoose