按动态字段对 mongo 集合进行排序

时间:2021-06-04 03:11:30

标签: mongodb

这是我的收藏:

[{"currency": "USD", "amount": 1}, 
{"currency": "EUR", "amount": 1}]

我想创建一个新字段并使用转化率动态排序我的收藏。

例如:1 欧元 = 1.2 美元。这将作为排序(升序)集合返回:

[{"currency": "USD", "amount": 1, "amount_in_USD": 1}, 
{"currency": "EUR", "amount": 1, "amount_in_USD": 1.2}]

1 个答案:

答案 0 :(得分:2)

db.getCollection('products').aggregate([
  {
      $addFields: {
        amount_in_USD: {
            $cond: [ {"$eq": ["$currency","EUR" ]},  { $multiply: [ "$amount", 1.2 ] },  "$amount" ]
        }
      }
  },
  {
      $sort: { amount_in_USD: -1 },
  }
])