【问题标题】:Conditional $sort in aggregation聚合中的条件 $sort
【发布时间】:2021-08-20 23:58:50
【问题描述】:

我想对价格进行条件排序,数据库中有两种价格,所以我检查sellTypefixed price还是bid

if(sellType===fixed price) 那么我想取正常价格但是, if(sellType===bid) 然后我想从存储在数组第 0 位的对象中获取价格。

所以我尝试进行聚合查询,分享我的代码 sn-p

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

我已经尝试了所有可能的解决方案,但无法从 bidInfo 数组中获取价格。 bidInfo 是一个对象数组,但我只想要第 0 个位置的对象(价格非常精确)

【问题讨论】:

标签: javascript node.js mongodb mongoose aggregation-framework


【解决方案1】:

你可以试试$arrayElemAt

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 2020-12-25
    • 2020-02-27
    • 1970-01-01
    • 2019-04-07
    相关资源
    最近更新 更多