-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
and.txt
82 lines (56 loc) · 2.39 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
====
$and
====
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
.. query:: $and
*Syntax*: ``{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }``
:query:`$and` performs a logical ``AND`` operation on an array
of *one or more* expressions (e.g. ``<expression1>``,
``<expression2>``, etc.) and selects the documents that satisfy
*all* the expressions in the array. The :query:`$and` operator
uses *short-circuit evaluation*. If the first expression
(e.g. ``<expression1>``) evaluates to ``false``, MongoDB will not
evaluate the remaining expressions.
.. note::
MongoDB provides an implicit ``AND`` operation when specifying a
comma separated list of expressions.
Examples
--------
``AND`` Queries With Multiple Expressions Specifying the Same Field
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following example:
.. code-block:: javascript
db.inventory.find( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } )
This query will select all documents in the ``inventory``
collection where:
- the ``price`` field value is not equal to ``1.99`` **and**
- the ``price`` field exists.
This query can be also be constructed with an implicit ``AND``
operation by combining the operator expressions for the ``price``
field. For example, this query can be written as:
.. code-block:: javascript
db.inventory.find( { price: { $ne: 1.99, $exists: true } } )
``AND`` Queries With Multiple Expressions Specifying the Same Operator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following example:
.. code-block:: javascript
db.inventory.find( {
$and: [
{ $or: [ { qty: { $lt : 10 } }, { qty : { $gt: 50 } } ] },
{ $or: [ { sale: true }, { price : { $lt : 5 } } ] }
]
} )
This query will select all documents where:
- the ``qty`` field value is less than ``20`` or greater than ``50``, **and**
- the ``sale`` field value is equal to ``true`` **or** the ``price``
field value is less than ``5``.
This query cannot be constructed using an implicit ``AND`` operation,
because it uses the :query:`$or` operator more than once.
.. seealso::
:method:`~db.collection.find()`, :method:`~db.collection.update()`,
:query:`$ne`, :query:`$exists`, :update:`$set`.