If you want to project all the fields that does not have an empty text string, use the following query.
db.collection.aggregate([
{
$unwind: "$array_of_objects"
},
{
$project: {
array_of_objects: {
$arrayToObject: {
$filter: {
input: {
$objectToArray: "$array_of_objects"
},
cond: {
$ne: [
"$$this.v.text",
""
]
}
}
}
}
}
}
])
MongoDB Playground
If you want to to project all the fields that does not have an empty text string and empty array, just add a $ne empty array check, use the following query:
MongoDB Playground
If you want to remove any document that has an empty text string, use an additional $match stage to remove documents with empty text string.
db.collection.aggregate([
{
$unwind: "$array_of_objects"
},
{
$project: {
array_of_objects: {
$filter: {
input: {
$objectToArray: "$array_of_objects"
},
cond: {
$and: [
{
$ne: [
"$$this.v.text",
""
]
},
{
$ne: [
"$$this.v",
[]
]
}
]
}
}
}
}
},
{
$match: {
"array_of_objects.v.text": {
$exists: true
}
}
},
{
$project: {
array_of_objects: {
"$arrayToObject": "$array_of_objects"
}
}
}
])
MongoDB Playground