我有一个集合,其中包含需要拉平的平衡对象,并且该对象中的字段需要根据集合中的另一个标志重新命名-
[
{
"id": "1234",
"documentType": "IV",
"balance": {
"total": 100,
"openBalance": 60,
"paid": 40
}
},
{
"id": "9012",
"documentType": "CM",
"balance": {
"total": 50,
"applied": 0,
"available": 50
}
}
]
如果documentType =="IV",那么"balance. payed"将成为$$ROOT中的"totalAmountPaid",而如果是"CM",那么"balance.applied"将重命名为appliedAmount,将"balance. availableAmount"重新命名为availableAmount,因此压平余额对象后的最终收款变成-
[
{
"id": "1234",
"documentType": "IV",
"total": 100,
"openBalance": 60,
"totalAmountPaid": 40
},
{
"id": "9012",
"documentType": "CM",
"total": 50,
"appliedAmount": 0,
"availableAmount": 50
}
]
我try 像这样使用$set和$cond,但它不起作用,而且我对MongoDB命令也不是很熟悉-
db.collection.aggregate([
{
$set: {
$cond: {
if: {
$eq: [
"$documentType",
"IV"
]
},
then: {
"total": "$balance.total",
"openBalance": "$balance.openBalance",
"totalAmountPaid": "$balance.paid",
"balance": "$$REMOVE"
},
else: {
"$total": "$balance.total",
"$availableAmount": "$balance.available",
"$appliedAmount": "$balance.applied",
"balance": "$$REMOVE"
}
}
}
}
])