[英]MONGODB Aggregation Convert if field exists or do nothing
I need convert a field in MONGODB but if the field/path doesn't exist, I don't want it to be created.我需要转换 MONGODB 中的一个字段,但如果该字段/路径不存在,我不想创建它。 I try using $$remove, $setfield, but without success in both.我尝试使用 $$remove、$setfield,但都没有成功。 Please, someone with knowledge on MongoDB, help me.请 MongoDB 上有知识的人帮助我。
Note: check the images please.注意:请检查图像。 I tried to use $$remove instead of "null" but still nothing我尝试使用 $$remove 而不是 "null" 但仍然没有
[{
"$addFields": {
"fieldExists": {
"$cond": [{
"$ifNull": ["$documentoAlterado.nfeProc.NFe.infNFe.total.ICMSTot.vBC", null]
}, true, false]
}
}
}, {
"$addFields": {
"convertResult": {
"$cond": [{
"$eq": ["$fieldExists", true]
}, {
"$convert": {
"input": "$documentoAlterado.nfeProc.NFe.infNFe.total.ICMSTot.vBC",
"to": "decimal",
"onError": "$documentoAlterado.nfeProc.NFe.infNFe.total.ICMSTot.vBC",
"onNull": "$documentoAlterado.nfeProc.NFe.infNFe.total.ICMSTot.vBC"
}
}, null]
}
}
}, {
"$addFields": {
"documentoAlterado.nfeProc.NFe.infNFe.total.ICMSTot.vBC": "$convertResult"
}
}
]
exists convert result replceRoot exists转换结果replceRoot
ExistsMongoPlaygroud NotExistsMongoPLayground存在MongoPlaygroud NotExistsMongoPLayground
Use $set
to conditionally update the documentoAlterado
object with the $convert
result.使用$set
有条件地使用$convert
结果更新documentoAlterado
object。
db.collection.aggregate([
{
"$addFields": {
"documentoAlterado.nfeProc.NFe.infNFe.total.ICMSTot.vBC": {
"$convert": {
"input": "$documentoAlterado.nfeProc.NFe.infNFe.total.ICMSTot.vBC",
"to": "decimal",
"onError": "$$REMOVE",
"onNull": "$$REMOVE"
}
}
}
},
{
"$set": {
"documentoAlterado": {
"$cond": {
"if": {
$eq: [
{},
"$documentoAlterado.nfeProc.NFe.infNFe.total.ICMSTot"
]
},
"then": {
// keep the other fields you want
"cteProc": "$documentoAlterado.cteProc"
},
"else": "$documentoAlterado"
}
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.