这是我的收藏:
[{"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}]
答案 0 :(得分:2)
db.getCollection('products').aggregate([
{
$addFields: {
amount_in_USD: {
$cond: [ {"$eq": ["$currency","EUR" ]}, { $multiply: [ "$amount", 1.2 ] }, "$amount" ]
}
}
},
{
$sort: { amount_in_USD: -1 },
}
])