检查可以为 null 的嵌套 属性

Checking nested property that can be null

我的 collection 中有以下数据:

{ colour: { r: 0, g: 0, b: 0 }},
{ colour: null },

如何找到所有在某些值之间具有 colour == nullcolor.r 的文档?

我试过了

.find({ where: { $or: [{colour: null}, {"colour.r": {$gt: 0, $lt: 100}}]}})

当然这给了我 cannot read property 'r' of null 空行。

只有在没有其他方式表达您的查询时才使用$where

db.test.find({$or: [{"colour": null}, {"colour.r": {$gt: 0, $lt: 100}}]})

除非不需要单个查询,否则您可以 运行 2 个查询:

  1. 查找所有文档where color == null
  2. 查找所有文档where color != null and color between 0 and 100

为了完整起见:

db.test.find({$nor: [{"colour.r": {$lte: 0}}, {"colour.r": {$gte: 100}}]})

$nor 将匹配所有 未通过 表达式的文档。

在这里,您不必显式测试 null,因为它既不大于也不小于任何数字——因此,测试将失败,就像 中的任何数字一样 范围 (0,100)1


1独家。如果您需要查找 [0,100] 范围内的所有文档,请将 $gte(resp. $lte)替换为 $gt(resp. $lt)。