![](/img/trans.png)
[英]How to remove empty string and arrays from objects inside an array? MongoDB Aggegation
[英]How to remove empty string and arrays from objects inside an object with the mongodb aggregation pipeline?
我想從對象內的對象中刪除任何具有空text
字符串的文檔。 有沒有辦法用 MongoDB 聚合框架來做到這一點? 在這種情況下,它將是object_1
和object_2
的text
。
"array_of_objects":[{
"city": "Seattle",
"array_1": [],
"object_1":{
"name": "Mandy",
"text" "",
},
"object_2":{
"name": "Billy",
"text" "",
},
}]
如果要投影所有沒有空text
字符串的字段,請使用以下查詢。
db.collection.aggregate([
{
$unwind: "$array_of_objects"
},
{
$project: {
array_of_objects: {
$arrayToObject: {
$filter: {
input: {
$objectToArray: "$array_of_objects"
},
cond: {
$ne: [
"$$this.v.text",
""
]
}
}
}
}
}
}
])
如果要投影所有沒有空text
字符串和空數組的字段,只需添加一個$ne
空數組檢查,使用以下查詢:
如果要刪除任何具有空文本字符串的文檔,請使用額外的 $match 階段來刪除具有空文本字符串的文檔。
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"
}
}
}
])
您可以使用$pull
運算符刪除text
字段為空的子文檔 -
var query = {};
var update = {
$pull: {
array_of_objects: {
'object_1.text': '',
'object_2.text': ''
}
}
};
var options = {
multi: true
};
db.collection.update(query, update, options);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.