/
ifNull.txt
69 lines (50 loc) · 1.82 KB
/
ifNull.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
=====================
$ifNull (aggregation)
=====================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. expression:: $ifNull
Evaluates an expression and returns the value of the expression if
the expression evaluates to a non-null value. If the expression
evaluates to a null value, including instances of undefined values
or missing fields, returns the value of the replacement expression.
The :expression:`$ifNull` expression has the following syntax:
.. code-block:: javascript
{ $ifNull: [ <expression>, <replacement-expression-if-null> ] }
The arguments can be any valid :ref:`expression
<aggregation-expressions>`. For more information on expressions, see
:ref:`aggregation-expressions`.
Example
-------
The following example use a ``inventory`` collection with the following
documents:
.. code-block:: javascript
{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 }
{ "_id" : 2, "item" : "abc2", description: null, qty: 200 }
{ "_id" : 3, "item" : "xyz1", qty: 250 }
The following operation uses the :expression:`$ifNull` expression to
return either the non-null ``description`` field value or the string
``"Unspecified"`` if the ``description`` field is null or does not
exist:
.. code-block:: javascript
db.inventory.aggregate(
[
{
$project: {
item: 1,
description: { $ifNull: [ "$description", "Unspecified" ] }
}
}
]
)
The operation returns the following results:
.. code-block:: javascript
{ "_id" : 1, "item" : "abc1", "description" : "product 1" }
{ "_id" : 2, "item" : "abc2", "description" : "Unspecified" }
{ "_id" : 3, "item" : "xyz1", "description" : "Unspecified" }