mongodb - 在mongo中如何匹配不是空元素列表的字段?
问题描述
我有字段 x 可以是[[], [], ...]
或者["", "", ....]
我想将它们过滤掉并保持文档至少有 1 个非空列表或 1 个非空字符串。例如[[], [1,2], [], ...]
解决方案
This is an aggregation query which filters out collection documents with the array field x
, having elements with all empty strings or all empty arrays.
db.collection.aggregate([
{
$addFields: {
filtered: {
$filter: {
input: "$x",
as: "e",
cond: {
$or: [
{ $and: [
{ $eq: [ { "$type": "$$e" }, "array" ] },
{ $gt: [ { $size: "$$e" }, 0 ] }
] },
{ $and: [
{ $eq: [ { "$type": "$$e" }, "string" ] },
{ $gt: [ { $strLenCP: "$$e" }, 0 ] }
] }
]
}
}
}
}
},
{
$match: {
$expr: { $gt: [ { $size: "$filtered" }, 0 ] }
}
},
{
$project: { filtered: 0 }
}
])
Reference: Various aggregation operators ($size
, $type
, $strLenCP
, etc.) used.
推荐阅读
- html - 如何链接到展开/折叠部分并自动打开?
- reactjs - “npm install”不会安装所有依赖项
- html - 防止浮动 div 换行错误
- c++ - 什么可能导致以下代码中出现“未定义的引用”错误?
- python - 为什么 tox 面临 Pytest 版本冲突?
- python - 从一个表中提取小时值并在另一个表中填充一小时增量的“桶”的函数
- spock - 如何从 spock 测试框架访问 application.yml 文件
- mysql - 计算数据类型 TIME 的十进制数
- java - 在 Android API28 上关闭应用程序时,WorkManager 不会定期运行
- javascript - 在 JavaScript 中实现节点存储功能