【问题标题】:Speed up subdocument access in mongodb加快 mongodb 中的子文档访问
【发布时间】:2017-02-15 13:37:29
【问题描述】:

我有一个集合,我不想通过聚合查询仅访问特定的子文档。

考虑每个文件描述一个国家的文件,每个城市都有一个子文件。现在我只想访问慕尼黑的子文档。

{
_id: "123abc",
name: "Germany",
"someAttribute": ...
cities: [
    {
        "name": "Berlin", 
        "someAttribute": ...
    },
    {
        "name": "Munich", 
        "someAttribute": ...
    },
    {
        "name": "Bonn"
    },
    ...
]
}

我知道我可以添加一个索引来加快检索包含慕尼黑相关子文档的文档。我正在寻找的是一种加快子文档本身检索的方法。因为对于大文档,mongodb扫描文档并提取相关子文档仍然需要很长时间。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    鉴于我们在 mongodb 中有这个文档

    {
        _id: "123abc",
        name: "Germany",
        "someAttribute": ["a","b","c"],
        cities: [
            {
                "name": "Berlin", 
                "someAttribute": ["a","b","c"]
            },
            {
                "name": "Munich", 
                "someAttribute": ["a","b","c"]
            },
            {
                "name": "Bonn"
            }
        ]
    }
    

    然后我们可以进行如下聚合查询

    db.test.aggregate([
        { $match: { "cities.name" : "Berlin" } },
        { $unwind: "$cities" },
        { $match: { "cities.name" : "Berlin" } },
        { $project: { "city" : "$cities" } }
    ]);
    

    这会将返回文档的大小限制为仅城市,从而节省带宽和传输时间。

    但是你应该确保 city.name 有一个索引

    db.test.createIndex( { "cities.name" : 1 } );
    

    【讨论】:

    • 是的 - 您的解决方案正是我所知道的。问题是 mongo 仍然必须扫描文档中的所有城市并找到正确的城市 - 我正在寻找一种方法让 mongo 只读取包含我正在寻找的城市的文档的相关部分。跨度>
    • 你的正确,mongodb会将整个文档(但只有匹配的文档)加载到内存中以对其进行操作。很确定没有办法解决这个问题,你可以对你的文档进行不同的建模吗?
    猜你喜欢
    • 2013-11-08
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2023-03-28
    相关资源
    最近更新 更多