存储许多没有冗余字段的小文档

Storing many small documents without redundant fields

这是 mongoDB 中经典的许多小文档与少数大文档问题的一个子集。现在我有一个很大的 mongodb 文档,如下所示:

//Collection: Everything
{
    _id: "1",
    date: Date(...),
    target: "192.168.0.7"
    tests: [
        {
            name: "Speed Test",
            components: [
                {
                    name: "Upload Test"
                    results: [ { "upload_speed_Mbps" : 5 }, ... ]
                },
                {
                    name: "Download Test"
                    results: [ ... ]
                },
                ...
            ]
        },
        ...
    ]
}

问题是很难利用 mongoDB 的聚合功能和这样的文档结构,因为如果我想要,比方说,记录在给定目标之间的所有上传速度的数组两个日期,上传速度统计数据嵌套了 3 个数组,mongo 不知道如何找到它,除非我进行三重展开(我认为这是一项代价高昂的操作)。

因此,better/faster mongoDB 似乎有 collection 个像这样的小文档:

//Collection: Suites
{
    _id: "1",
    date: Date(...),
    target_ip: "192.168.0.7"
    tests: [
        "1a",
        "2a",
        "3a",
        ...
    ]
}

//Collection: Tests
{
    _id: "1a",
    name: "Speed Test",
    components: [
        "1b",
        "2b",
        "3b",
        ...
    ]
}

//Collection: Components
{
    _id: "1b",
    name: "Upload Test",
    results: [
        "1c",
        "2c",
        "3c",
        ...
    ]
}

//Collection: Results
{
    _id: "1c",
    name: "upload_speed_Mbps",
    value: 5
}

这样我就可以直接聚合跨结果文档。现在我的问题是,如果我想快速汇总两个日期之间给定目标上发生的 collection 上传速度,我唯一的选择是在其中包含 datetarget 字段Results collection 中的每个文件?当信息已经可以在顶级文档中访问时,这似乎是多余的。

我假设我可以:

  1. 我的子文档中有冗余信息以获得快速聚合

  1. 我的子文档中没有冗余信息,但由于昂贵的展开操作而失去了快速聚合?

$unwind 当您对本身具有大型数组或大型嵌套数组的大型文档集合执行操作时,操作的成本通常很高。

对于此查询,您可以使用原始文档结构并简单地 $match for the target and date range right at the beginning. That limits the size of the data being handled with the $unwind. You can also $project 进一步限制聚合处理的数据量。这应该会大大降低查询成本。

如果您仍然希望按照概述的方式将所有组件分开,那么是的,您需要在要查询的文档中包含您希望查询的信息。