【问题标题】:How to project an element of a nested indexed, non-associative array?如何投影嵌套索引非关联数组的元素?
【发布时间】:2021-07-06 21:21:11
【问题描述】:

我有以下文档结构(一个没有键的 PHP 索引数组):

Array
(
    [0] => Array
        (
            [country] => Europe
            [year] => 1997
            [id] => 7600522
        )

    [1] => Array
        (
            [country] => Europe
            [year] => 1997
            [id] => 820426
        )

    [2] => Array
        (
            [country] => France
            [year] => 1997
            [id] => 12363810
        )
)

我正在寻找一个选项来仅投影每个嵌套(索引)数组的 [id] 元素。我该怎么做?

我读到了 $$elemMatch$slice 运算符,但它们似乎不是我需要的。

【问题讨论】:

  • @Sammitch,我不想将未优化的文档带到网络上,并在服务器端将它们作为数组处理。相反,我只想在查询级别投影我需要的那些元素。不过还是谢谢。

标签: php arrays mongodb mongodb-query projection


【解决方案1】:

通过 MongoDB 论坛进行数小时研究,检查我的数据的不同表示后,我注意到我的问题中提到的 PHP 数组的 JSON 表示在语义上是不同的,并且不包含 PHP 数组中的索引。我使用json_ecnode() tp 将我的索引 PHP 数组转换为 JSON:

[
    {
        "country": "Europe",
        "year": 1997,
        "id": 7600522,
    },
    {
        "country": "Europe",
        "year": 1997,
        "id": 820426,
    },
    {
        "country": "France",
        "year": 1997,
        "id": 12363810,
    }
]

注意,JSON 中没有像 PHP 的 print_r() 显示的那样的数组索引。

其余的相当容易。我运行了查询:

$options = array(
  'limit' => 3,
  'projection' => array(
    '_id' => 0,
    'id' = >1
  )
);

$cursor = $mongodb->mycollection->find(array(), $options);

这给我带来了想要的数据集。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2015-05-12
    • 2018-02-20
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多