duanquan1243
2019-03-05 09:32
浏览 292

如何将数组中存在的值与mongo中的字段进行匹配

I have this data set in 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"
      }
    ]
  }
},

Here i would like to perform an equals to check between answer and result.options.id and if the value matches it should return result.options.option

So that the desired result is

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

So far i have tried this

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

Any clue as to what i am doing wrong . My code always returns the else statement

</div>
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题