首页 > 解决方案 > 猫鼬 - 查询子文档中的数组值

问题描述

我正在使用猫鼬。我的数据库中有以下文档:

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",
}

我会非常感谢任何形式的帮助!

标签: mongodbmongoose

解决方案


您可以使用聚合

  • $filter从数组中过滤非空 deletedAt 并$set有助于添加为新字段
  • $match删除空数组文档

这是代码

db.collection.aggregate([
  {
    "$set": {
      "answers": {
        "$filter": {
          "input": "$answers",
          "cond": {
            $ne: [ "$$this.deletedAt", null ]
          }
        }
      }
    }
  },
  {
    $match: {
      $expr: {
        $ne: [ "$answers", [] ]
      }
    }
  }
])

工作Mongo游乐场


推荐阅读