0

I wanted conditional sort on price, There are two types of price in the database, so I am checking whether the sellType is fixed price or bid,

if(sellType===fixed price) then I want to fetch the normal price but, if(sellType===bid) then I want to fetch the price from the object which is stored at 0th position in the array.

So I've tried to make aggregated query, sharing my code snippet

{
  $addFields: {
    sortedPrice: {
      $cond:  {
        if: {
          $eq: ["$itemDetail.sellType","fixed price"]
        },
        then: '$itemDetail.price',
        else:  '$itemDetail.bidInfo[0].price',
      }
    }
  }
}

I've tried all the possible solutions but not able to fetch the price from the bidInfo array. bidInfo is an array of objects but I want only the 0th position object (price to be very precise)

1

1 Answer 1

0

You can try with $arrayElemAt,

 {
        $addFields: {
            sortedPrice: {
                $cond: {
                    if: {
                        $eq: ['$itemDetail.sellType', 'fixed price'],
                    },
                    then: '$itemDetail.price',
                    else: { $arrayElemAt: ['$itemDetail.bidInfo.price', 0] },
                },
            },
        },
    },
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.