Reputation: 71
I want to delete the empty strings and empty arrays within a document. Is there a way to do this with the MongoDB Aggregation Framework? Here is an example of an incoming document:
"item": [{
"array_objects":[{
"text": '',
"second_text": '',
"empty_array": [],
"empty_array_2":[],
}]
}]
Upvotes: 1
Views: 427
Reputation: 1419
If you want to project all the fields that are not empty string or empty array, use $filter
You can try the below aggregation query:
db.collection.aggregate([
{
$unwind: "$item"
},
{
$unwind: "$item.array_objects"
},
{
$project: {
item: {
$arrayToObject: {
$filter: {
input: {
$objectToArray: "$item.array_objects"
},
cond: {
$and: [
{
$ne: [
"$$this.v",
""
]
},
{
$ne: [
"$$this.v",
[]
]
}
]
}
}
}
}
}
}
])
Upvotes: 2