Is there an elseif thing in MongoDB to $cond while aggregating

前端 未结 3 2090
忘了有多久
忘了有多久 2021-02-01 16:19

So I need a custom field calculated in MongoDB as follows

if( field1 ==\"A\")  ->customfield=10
else if(field1 ==\"B\"  )->customfield=20
else (field1 ==\"         


        
3条回答
  •  长发绾君心
    2021-02-01 16:59

    if you are using only object then

    {
        $cond: {
            $and: [
                { if: { $eq: ["$$field1", 'A'] }, then: '10', else: 15 },
                { if: { $eq: ["$$field1", 'B'] }, then: '20', else: 15 },
                { if: { $eq: ["$$field1", 'C'] }, then: '10', else: 15 },
            ]
        }
    }
    

    And if you are Using Array find Data

    {
        $map: {
            input: "$fields", as: "field1", in: {
                $cond: {
                    $and: [
                        { if: { $eq: ["$$field1", 'A'] }, then: '10', else: 15 },
                        { if: { $eq: ["$$field1", 'B'] }, then: '20', else: 15 },
                        { if: { $eq: ["$$field1", 'C'] }, then: '10', else: 15 },
                    ]
                }
            }
        }
    }
    

提交回复
热议问题