python - 如何从数组内的对象中删除空字符串和数组?MongoDB 聚合
问题描述
我想删除文档中的空字符串和空数组。有没有办法使用 MongoDB 聚合框架来做到这一点?以下是传入文档的示例:
"item": [{
"array_objects":[{
"text": '',
"second_text": '',
"empty_array": [],
"empty_array_2":[],
}]
}]
解决方案
如果要投影所有非空字符串或空数组的字段,请使用$filter
您可以尝试以下聚合查询:
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",
[]
]
}
]
}
}
}
}
}
}
])
推荐阅读
- c++ - 带有 GDB 调试器的 VS Code 内存视图
- swift - 为什么我不能扩展 IntegerType?
- r - 我希望根据每个分组级别内的子列表保留/丢弃 PURRR 嵌套列表中的项目
- gitlab-api - 如何通过 id 检索 gitlab 问题?
- java - org.apache.commons.lang3.time.DateFormatUtils.format() 线程安全吗?
- python - 如何在 Selenium 上的 Internet Explorer 上保留登录凭据
- google-cloud-platform - 控制GPU机器从一个功能启动和停止?
- jquery - 收集所有复选框的所有值以通过ajax
- reactjs - 是否可以将 react-konva 应用到 React Native 项目中?
- mysql - MySQL 不相关的列或使用行号连接表