使用mongoose从javascript对象中删除空数组



我有一个数据库集合,看起来像这样,如何删除这个空数组。

最初我有对象在这个(色调)数组它看起来像这样

"HUE": [{
"chartId": "timeseries",
"name": "TS",

}]

,但在删除对象之后,它不删除空数组

{

"userId": "adam",
"charts": {
"HUE": [],
"Color": [{
"chartId": "one",
"name": "TS",

}]
}
}

p。S我只想在HUE数组为空时删除它

delChartObj.updateOne(
{ 'userId': userId },
{ $pull: query } // this line actually find the chartId and delete it 
// after the above line, I actually want to check, if after del the object , array became empty, then delete the array too
, function (err, obj) {
if (err) { res.send.err }
res.status(200).send("Deleted Successfully");
});
db.collection.update({userId, 'charts.HUE': {$exists:true, $size:0}}, { $unset: { 'charts.HUE': 1 } })

它工作->https://mongoplayground.net/p/uqU7d0Kp2eL

更新:问题改变了,这个解决方案不完全正确。用户必须询问更多细节。

如果要过滤数组,然后如果为空则删除数组,可以执行以下操作

db.collection.update(
{
"$expr" : {
"$eq" : [ "$userId", "adam" ]
}
},
[ {
"$addFields" : {
"charts.HUE" : {
"$filter" : {
"input" : "$charts.HUE",
"as" : "hue",
"cond" : {
"$ne" : [ "$$hue.chartId", "timeseries" ]
}
}
}
}
}, {
"$addFields" : {
"charts.HUE" : {
"$cond" : [ {
"$eq" : [ {
"$size" : "$charts.HUE"
}, 0 ]
}, "$$REMOVE", "$charts.HUE" ]
}
}
} ]
)

此处测试代码

它的管道更新需要MongoDB>= 4.2管道更新非常强大,但对于简单的更新,它们可能会更复杂。

$$REMOVE是一个系统变量,如果一个字段得到这个值,它将被删除。这里字段只有在数组为空时才会得到这个值。

最新更新