Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking nested property that can be null

I've the following data in my collection:

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

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

I've 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 rows.

like image 396
eithed Avatar asked May 31 '15 16:05

eithed


People also ask

How do I check if an empty object is nested?

Use Object. Object. keys will return an array, which contains the property names of the object. If the length of the array is 0 , then we know that the object is empty.

Why is null better than optional?

In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional class forces you to think about the case when the value is not present.

Which is the correct way of accessing values of nested objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.


3 Answers

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

db.test.find({$or: [{"colour": null}, {"colour.r": {$gt: 0, $lt: 100}}]})
like image 148
styvane Avatar answered Sep 22 '22 14:09

styvane


For sake of completeness:

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

$nor will match all documents that fail the expressions.

Here, you don't have to explicitly test for null as it is neither greater nor lower than any number -- hence, will fail the tests, just like any number in the range (0,100)1


1Exclusive. If you need to find every document in the range [0,100] inclusive, replace $gte (resp. $lte) by $gt (resp. $lt).

like image 34
Sylvain Leroux Avatar answered Sep 19 '22 14:09

Sylvain Leroux


Unless don't need a single query, you could run 2 queries:

  1. Find all documents where color == null
  2. Find all documents where color != null and color between 0 and 100
like image 24
Barny Avatar answered Sep 20 '22 14:09

Barny