【问题标题】:How to match values that are present inside an array to a field in mongo如何将数组中存在的值与mongo中的字段匹配
【发布时间】:2019-03-05 09:32:12
【问题描述】:

我在 mongo 中有这个数据集

{
  _id: {
    question_id: 3
  },
  data: {
    answer: 11,
    count: 114,
    result: [
      {
        _id: 3,
        question: "What is your age group?",
        options: [
          {
            id: 10,
            option: "<18"
          },
          {
            id: 11,
            option: "18-24"
          },
          {
            id: 12,
            option: "24-35"
          },
          {
            id: 13,
            option: ">35"
          }
        ],
        type: "Radio"
      }
    ]
  }
},

在这里我想在answerresult.options.id 之间执行equals to 检查,如果值匹配,它应该返回result.options.option

这样想要的结果就是

{
  _id: {
    question_id: 3
  },
  data: {
    answer:'18-24',
    count: 114,
    
  }
},

到目前为止我已经尝试过这个

'$project'=>[
  'res'=>[
    '$map'=>[
      'input'=>'$data.result.options',
      'as'=>'dt',
      'in'=>[
        '$cond'=>[
          'if'=>[
            '$eq'=>[
              '$$dt.id',
              '$data.answer'
            ]
          ],
          'then'=>'$$dt.option',
          'else'=>'$$dt.id'
        ]
      ]
    ]
  ]
]

关于我做错了什么的任何线索。我的代码总是返回 else 语句

【问题讨论】:

    标签: php mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你很接近,但有几件事不太对:

    [ '$project'=> [
      'data' => [
        'answer' => [
          '$let' => [
            'vars' => [
              'res' => [
                '$reduce' => [
                  'input' => '$data.result.options',
                  'initialValue' => [],
                  'in' => [ '$concatArrays': [ '$$value', '$$this' ] ]
                ]
              ]
            ],
            'in' => [
              '$arrayElemAt' => [
                '$$res.option',
                [ '$indexOfArray': [ '$$res.id', '$data.answer' ] ]
              ]
            ]
          ]
        ],
        'count' => '$data.count'
      ]
    ]]
    

    '$data.result.options' 的路径实际上在嵌套数组中,因此为了让任何“数组操作”在 'options' 的内部值中工作,您需要“展平”该数组结构成一个奇异数组。

    为此,您可以使用$reduce$concatArrays。这也在$let 块中得到了演示,因为您想在以后的一些操作中使用这个“结果数组”

    提取单个值最简单的方法是通过$indexOfArray'data.answer' 找到数组的匹配索引,然后从“结果数组”中提取'option' 值 em> 之前使用 $arrayElemAt 为该值处理过,当然指向匹配的“索引”。

    $indexOfArray 运算符在这里是可靠的,只要您始终得到与文档数组中存在的 'data.answer' 值匹配的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 2021-07-12
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 2020-10-16
      相关资源
      最近更新 更多