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

    评论

报告相同问题?

悬赏问题

  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决
  • ¥15 关于华为5g模块mh5000-31接线问题
  • ¥15 keil L6007U报错
  • ¥15 webapi 发布到iis后无法访问
  • ¥50 occi的线程池创建