Validating a nested property that may be null

I have the following data in my collection:

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

How can I find all documents with colour == null or color.r between some values?

I tried

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

but of course this gives me cannot read property 'r' of null for null strings.

+5
source share
3 answers

Use $where only if there is no other way to express your request

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

If you do not need one request, you can run 2 requests:

  • Find all documents where color == null
  • Find all documents where color != null and color between 0 and 100
+1
source

For completeness:

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

$nor will match all documents that invoke expressions.

Here you do not need to explicitly check the null value, since it is not more or less than any number - therefore, tests will not pass, like any number in the range (0,100) 1


<sub> 1 Exclusive. If you need to find every document in the range [0,100] inclusive, replace $gte (respectively $lte ) with $gt (respectively $lt ).

+1
source

All Articles