Reputation: 71
I want to remove any document that has an empty text
string from an object within an object. Is there a way to do this with the MongoDB Aggregation Framework? In this case it will be the text
within object_1
and object_2
.
"array_of_objects":[{
"city": "Seattle",
"array_1": [],
"object_1":{
"name": "Mandy",
"text" "",
},
"object_2":{
"name": "Billy",
"text" "",
},
}]
Upvotes: 0
Views: 1625
Reputation: 5853
You can use the $pull
operator to remove the sub-document whose text
fields are empty -
var query = {};
var update = {
$pull: {
array_of_objects: {
'object_1.text': '',
'object_2.text': ''
}
}
};
var options = {
multi: true
};
db.collection.update(query, update, options);
Upvotes: 0
Reputation: 1419
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",
""
]
}
}
}
}
}
}
])
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:
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"
}
}
}
])
Upvotes: 1