How to unset field(array) if its length after $pull operation equals 0 in MongoDB?
I need to do it using only 1 query. Is it possible?
There is no way in a regular update query, but You can try update with aggregation pipeline starting from MongoDB 4.2,
Consider this is a sample document and you want to pull "1" from array field:
{
"array": [1]
}
$filter to iterate loop of array and filter array that is not equal to "1"$cond to check after pull, is array field empty then remove by $$REMOVE otherwise nothing to dodb.collection.update(
{ "array": 1 },
[{
$set: {
array: {
$filter: {
input: "$array",
cond: { $ne: ["$$this", 1] }
}
}
}
},
{
$set: {
array: {
$cond: [
{ $eq: ["$array", []] },
"$$REMOVE",
"$array"
]
}
}
}]
)
The second alternate option,
$cond to check is array equal to the single element that we are going to pull [1] then remove array field otherwise go to $filter operation to remove single elementdb.collection.update(
{ "array": 1 },
[{
$set: {
array: {
$cond: [
{ $eq: ["$array", [1]] },
"$$REMOVE",
{
$filter: {
input: "$array",
cond: { $ne: ["$$this",1] }
}
}
]
}
}
}]
)