mongodb - 猫鼬 - 查询子文档中的数组值
问题描述
我正在使用猫鼬。我的数据库中有以下文档:
question: {
"id": "1",
"answers": [
{
"id": "11",
"deletedAt": "2021-05-28T20:23:30.409Z",
}
}
},
question: {
"id": "2",
"answers": [
{
"id": "22",
"deletedAt": null,
}
}
}
我正在尝试构建一个查询,该查询返回所有具有 deletedAt 值的 anwsers,因此不为空。我尝试了以下方法:
Question.find({ "answers.deletedAt": { $ne: null }});
这将返回所有问题。但是,我不仅想返回答案,而且只想返回在 deletedAt 字段中具有值的一次。
所以坚持上面的例子,我想要这个输出:
{
"id": "11",
"deletedAt": "2021-05-28T20:23:30.409Z",
}
我会非常感谢任何形式的帮助!
解决方案
您可以使用聚合
$filter
从数组中过滤非空 deletedAt 并$set
有助于添加为新字段$match
删除空数组文档
这是代码
db.collection.aggregate([
{
"$set": {
"answers": {
"$filter": {
"input": "$answers",
"cond": {
$ne: [ "$$this.deletedAt", null ]
}
}
}
}
},
{
$match: {
$expr: {
$ne: [ "$answers", [] ]
}
}
}
])
工作Mongo游乐场
推荐阅读
- reactjs - 尝试“读取”firebase 数据并将其呈现在 ReactJS 上
- reactjs - 定义不带样式组件的 CSS 变量
- django - 注释来自过滤的相关对象的值——案例、子查询或其他方法?
- idl - 在 IDL 中使用 IDLgrClipBoard 时,MacO 能否正确显示图像?
- angular - 延迟 *ngIf 语句
- sql - 需要通过连接 Oracle DB 中的多个表来创建空表
- html - 在某些缩放级别将绝对定位的 div 对齐 1px
- javascript - 如何将全日历视图设置为在当前日期前 1 周开始?
- html - 覆盖内容的动画
- r - R:如何在 MICE 插补后执行 add1-model 分析