-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
and.txt
136 lines (90 loc) · 2.69 KB
/
and.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
==================
$and (aggregation)
==================
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. expression:: $and
Evaluates one or more expressions and returns ``true`` if *all* of
the expressions are ``true`` or if run with no argument
expressions. Otherwise, :expression:`$and` returns ``false``.
:expression:`$and` syntax:
.. code-block:: javascript
{ $and: [ <expression1>, <expression2>, ... ] }
For more information on expressions, see
:ref:`aggregation-expressions`.
.. _and-boolean-behavior:
Behavior
--------
.. include:: /includes/extracts/fact-agg-boolean-and.rst
.. list-table::
:header-rows: 1
:widths: 70, 15, 15
* - Example
-
- Result
* - ``{ $and: [ 1, "green" ] }``
-
- ``true``
* - ``{ $and: [ ] }``
-
- ``true``
* - ``{ $and: [ [ null ], [ false ], [ 0 ] ] }``
-
- ``true``
* - ``{ $and: [ null, true ] }``
-
- ``false``
* - ``{ $and: [ 0, true ] }``
-
- ``false``
Error Handling
--------------
.. |and-or| replace:: ``$and``
.. |true-false| replace:: ``false``
.. include:: /includes/and-or-behavior.rst
.. code-block:: javascript
db.example.find( {
$and: [
{ x: { $ne: 0 } },
{ $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] } }
]
} )
Example
-------
Create an example ``inventory`` collection with these documents:
.. code-block:: javascript
db.inventory.insertMany([
{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 },
{ "_id" : 2, "item" : "abc2", description: "product 2", qty: 200 },
{ "_id" : 3, "item" : "xyz1", description: "product 3", qty: 250 },
{ "_id" : 4, "item" : "VWZ1", description: "product 4", qty: 300 },
{ "_id" : 5, "item" : "VWZ2", description: "product 5", qty: 180 }
])
This operation uses the :expression:`$and` operator to
determine if ``qty`` is greater than 100 *and* less than ``250``:
.. code-block:: javascript
db.inventory.aggregate(
[
{
$project:
{
item: 1,
qty: 1,
result: { $and: [ { $gt: [ "$qty", 100 ] }, { $lt: [ "$qty", 250 ] } ] }
}
}
]
)
The operation returns these results:
.. code-block:: javascript
{ "_id" : 1, "item" : "abc1", "qty" : 300, "result" : false }
{ "_id" : 2, "item" : "abc2", "qty" : 200, "result" : true }
{ "_id" : 3, "item" : "xyz1", "qty" : 250, "result" : false }
{ "_id" : 4, "item" : "VWZ1", "qty" : 300, "result" : false }
{ "_id" : 5, "item" : "VWZ2", "qty" : 180, "result" : true }