查询不存在某个字段的数据

10/25/2023 MongoDB

如果你想在 MongoDB 聚合查询中筛选出某个字段不存在的文档,你可以使用 $exists 来检查字段是否存在,然后使用 $match 阶段来筛选出符合条件的文档。
以下是如何执行这个操作:
假设你有以下的文档结构,其中一些文档中缺少 "fieldName" 字段:

{
  "_id": 1,
  "fieldName": "Value 1"
}
{
  "_id": 2,
  "otherField": "Value 2"
}
{
  "_id": 3,
  "fieldName": "Value 3"
}

你可以使用 $exists 来筛选出缺少 "fieldName" 字段的文档:

db.collection.aggregate([
  {
    $match: {
      fieldName: { $exists: false }
    }
  }
])

这个聚合查询的 $match 阶段使用 $exists 条件来筛选出那些 "fieldName" 字段不存在的文档。
查询的结果将包括 _id 为 2 的文档,因为它缺少 "fieldName" 字段。其他文档将被排除。
这样,你可以通过 $exists 和 $match 阶段来查询那些某个字段不存在的文档。