dping1968 2018-12-10 20:11
浏览 98

PHP - MongoDB:使用数组中的字段名称从子文档中检索字段

Consider an Array

$lettersArray = [A,C,E,G]

and my MongoDB Collection has the following structure.

{
    Collection : {
        letters:{
            A:{...},
            B:{...},
            ...
            Z:{...}
        }

    }
}

Consider that the Letter Sub document is a part of a larger collection. Hence I am using Aggregation. Right Now I have tried to project -

['$Collection.letters' => ['$elemMatch' => ['$in' => $lettersArray]]

and also tried

['Letters' => ['$in' => [$lettersArray,'$Collection.letters']]

But it didn't work.

In the End, I want result like the following:

 [
     Collection => [
        letters => [
            A => [...],
            C => [...],
            E => [...],
            G => [...]
        ]
    ]
]

Is there any way to do this?

  • 写回答

2条回答 默认 最新

  • duandang2123 2018-12-10 20:35
    关注

    In PHP you can use array_combine with array_fill to create the empty arrays.

    $lettersArray = ['A','C','E','G'];
    
    $letters = array_combine($lettersArray, array_fill(0,count($lettersArray), []));
    

    Array_fill creates an array from index 0, to the count of items in $lettersArray with the contents []

    Output:

    array(4) {
      ["A"]=>
      array(0) {
      }
      ["C"]=>
      array(0) {
      }
      ["E"]=>
      array(0) {
      }
      ["G"]=>
      array(0) {
      }
    }
    

    https://3v4l.org/TeoFv

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?