首页 > 解决方案 > 从 MongoDB 中的 Document (PHP) 中检索深度嵌套的子文档

问题描述

我有一个类似的集合:

{
'_id': ObjectId("5bc74908f2377d746g1e9983"),
components:{
    0: {
        index: 21,
        abc:22,
        sim: [
            {s_index:23},
            {hyx:45}
        ]
    },
    1: {
        index: 21,
        abc:22,
        sim: [
            {s_index:23},
            {hyx:45}
        ]
    }
   }
}

我正在尝试输出:

{
    index: 21,
    abc:22,
         sim: [
             {s_index:23},
             {hyx:45}
        ]
}

但是使用以下查询:

$Result = $templates -> findOne(
[
    '_id' => new \MongoDB\BSON\ObjectId("5bc74908f2377d746g1e9983")
],
['projection' => ['_id' => false, 'components.0' => true]]
);

我得到的输出为:

{
   components:{
    0: {
        index: 21,
        abc:22,
        sim: [
            {s_index:23},
            {hyx:45}
        ]
    }
    }
}

有没有办法获得所需的输出? 我试图只检索 的值,component.0但我得到了文档中的完整路径。

sim是一个对象数组。如果我只想在sim不是从组件到 sim 的路径中检索特定对象怎么办。这可以做到吗?

标签: phpmongodb

解决方案


推荐阅读