forked from mongodb/laravel-mongodb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery-builder.txt
596 lines (384 loc) · 13.1 KB
/
query-builder.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
.. _laravel-query-builder:
=============
Query Builder
=============
.. facet::
:name: genre
:values: tutorial
.. meta::
:keywords: php framework, odm, code example
The database driver plugs right into the original query builder.
When using MongoDB connections, you will be able to build fluent queries to
perform database operations.
For your convenience, there is a ``collection`` alias for ``table`` and
other MongoDB specific operators/operations.
.. code-block:: php
$books = DB::collection('books')->get();
$hungerGames =
DB::collection('books')
->where('name', 'Hunger Games')
->first();
If you are familiar with `Eloquent Queries <http://laravel.com/docs/queries>`__,
there is the same functionality.
Available operations
--------------------
**Retrieving all models**
.. code-block:: php
$users = User::all();
**Retrieving a record by primary key**
.. code-block:: php
$user = User::find('517c43667db388101e00000f');
**Where**
.. code-block:: php
$posts =
Post::where('author.name', 'John')
->take(10)
->get();
**OR Statements**
.. code-block:: php
$posts =
Post::where('votes', '>', 0)
->orWhere('is_approved', true)
->get();
**AND statements**
.. code-block:: php
$users =
User::where('age', '>', 18)
->where('name', '!=', 'John')
->get();
**NOT statements**
.. code-block:: php
$users = User::whereNot('age', '>', 18)->get();
**whereIn**
.. code-block:: php
$users = User::whereIn('age', [16, 18, 20])->get();
When using ``whereNotIn`` objects will be returned if the field is
non-existent. Combine with ``whereNotNull('age')`` to omit those documents.
**whereBetween**
.. code-block:: php
$posts = Post::whereBetween('votes', [1, 100])->get();
**whereNull**
.. code-block:: php
$users = User::whereNull('age')->get();
**whereDate**
.. code-block:: php
$users = User::whereDate('birthday', '2021-5-12')->get();
The usage is the same as ``whereMonth`` / ``whereDay`` / ``whereYear`` / ``whereTime``
**Advanced wheres**
.. code-block:: php
$users =
User::where('name', 'John')
->orWhere(function ($query) {
return $query
->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})->get();
**orderBy**
.. code-block:: php
$users = User::orderBy('age', 'desc')->get();
**Offset & Limit (skip & take)**
.. code-block:: php
$users =
User::skip(10)
->take(5)
->get();
**groupBy**
Selected columns that are not grouped will be aggregated with the ``$last``
function.
.. code-block:: php
$users =
Users::groupBy('title')
->get(['title', 'name']);
**Distinct**
Distinct requires a field for which to return the distinct values.
.. code-block:: php
$users = User::distinct()->get(['name']);
// Equivalent to:
$users = User::distinct('name')->get();
Distinct can be combined with **where**:
.. code-block:: php
$users =
User::where('active', true)
->distinct('name')
->get();
**Like**
.. code-block:: php
$spamComments = Comment::where('body', 'like', '%spam%')->get();
**Aggregation**
**Aggregations are only available for MongoDB versions greater than 2.2.x**
.. code-block:: php
$total = Product::count();
$price = Product::max('price');
$price = Product::min('price');
$price = Product::avg('price');
$total = Product::sum('price');
Aggregations can be combined with **where**:
.. code-block:: php
$sold = Orders::where('sold', true)->sum('price');
Aggregations can be also used on sub-documents:
.. code-block:: php
$total = Order::max('suborder.price');
.. note::
This aggregation only works with single sub-documents (like ``EmbedsOne``)
not subdocument arrays (like ``EmbedsMany``).
**Incrementing/Decrementing the value of a column**
Perform increments or decrements (default 1) on specified attributes:
.. code-block:: php
Cat::where('name', 'Kitty')->increment('age');
Car::where('name', 'Toyota')->decrement('weight', 50);
The number of updated objects is returned:
.. code-block:: php
$count = User::increment('age');
You may also specify more columns to update:
.. code-block:: php
Cat::where('age', 3)
->increment('age', 1, ['group' => 'Kitty Club']);
Car::where('weight', 300)
->decrement('weight', 100, ['latest_change' => 'carbon fiber']);
MongoDB-specific operators
~~~~~~~~~~~~~~~~~~~~~~~~~~
In addition to the Laravel Eloquent operators, all available MongoDB query
operators can be used with ``where``:
.. code-block:: php
User::where($fieldName, $operator, $value)->get();
It generates the following MongoDB filter:
.. code-block:: ts
{ $fieldName: { $operator: $value } }
**Exists**
Matches documents that have the specified field.
.. code-block:: php
User::where('age', 'exists', true)->get();
**All**
Matches arrays that contain all elements specified in the query.
.. code-block:: php
User::where('roles', 'all', ['moderator', 'author'])->get();
**Size**
Selects documents if the array field is a specified size.
.. code-block:: php
Post::where('tags', 'size', 3)->get();
**Regex**
Selects documents where values match a specified regular expression.
.. code-block:: php
use MongoDB\BSON\Regex;
User::where('name', 'regex', new Regex('.*doe', 'i'))->get();
.. note::
You can also use the Laravel regexp operations. These will automatically
convert your regular expression string to a ``MongoDB\BSON\Regex`` object.
.. code-block:: php
User::where('name', 'regexp', '/.*doe/i')->get();
The inverse of regexp:
.. code-block:: php
User::where('name', 'not regexp', '/.*doe/i')->get();
**ElemMatch**
The :manual:`$elemMatch </reference/operator/query/elemMatch//>` operator
matches documents that contain an array field with at least one element that
matches all the specified query criteria.
The following query matches only those documents where the results array
contains at least one element that is both greater than or equal to 80 and
is less than 85:
.. code-block:: php
User::where('results', 'elemMatch', ['gte' => 80, 'lt' => 85])->get();
A closure can be used to create more complex sub-queries.
The following query matches only those documents where the results array
contains at least one element with both product equal to "xyz" and score
greater than or equal to 8:
.. code-block:: php
User::where('results', 'elemMatch', function (Builder $builder) {
$builder
->where('product', 'xyz')
->andWhere('score', '>', 50);
})->get();
**Type**
Selects documents if a field is of the specified type. For more information
check: :manual:`$type </reference/operator/query/type/#op._S_type/>` in the
MongoDB Server documentation.
.. code-block:: php
User::where('age', 'type', 2)->get();
**Mod**
Performs a modulo operation on the value of a field and selects documents with
a specified result.
.. code-block:: php
User::where('age', 'mod', [10, 0])->get();
MongoDB-specific Geo operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**Near**
.. code-block:: php
$bars = Bar::where('location', 'near', [
'$geometry' => [
'type' => 'Point',
'coordinates' => [
-0.1367563, // longitude
51.5100913, // latitude
],
],
'$maxDistance' => 50,
])->get();
**GeoWithin**
.. code-block:: php
$bars = Bar::where('location', 'geoWithin', [
'$geometry' => [
'type' => 'Polygon',
'coordinates' => [
[
[-0.1450383, 51.5069158],
[-0.1367563, 51.5100913],
[-0.1270247, 51.5013233],
[-0.1450383, 51.5069158],
],
],
],
])->get();
**GeoIntersects**
.. code-block:: php
$bars = Bar::where('location', 'geoIntersects', [
'$geometry' => [
'type' => 'LineString',
'coordinates' => [
[-0.144044, 51.515215],
[-0.129545, 51.507864],
],
],
])->get();
**GeoNear**
You can make a ``geoNear`` query on MongoDB.
You can omit specifying the automatic fields on the model.
The returned instance is a collection, so you can call the `Collection <https://laravel.com/docs/9.x/collections>`__ operations.
Make sure that your model has a ``location`` field, and a
`2ndSphereIndex <https://www.mongodb.com/docs/manual/core/2dsphere>`__.
The data in the ``location`` field must be saved as `GeoJSON <https://www.mongodb.com/docs/manual/reference/geojson/>`__.
The ``location`` points must be saved as `WGS84 <https://www.mongodb.com/docs/manual/reference/glossary/#std-term-WGS84>`__
reference system for geometry calculation. That means that you must
save ``longitude and latitude``, in that order specifically, and to find near
with calculated distance, you ``must do the same way``.
.. code-block::
Bar::find("63a0cd574d08564f330ceae2")->update(
[
'location' => [
'type' => 'Point',
'coordinates' => [
-0.1367563,
51.5100913
]
]
]
);
$bars = Bar::raw(function ($collection) {
return $collection->aggregate([
[
'$geoNear' => [
"near" => [ "type" => "Point", "coordinates" => [-0.132239, 51.511874] ],
"distanceField" => "dist.calculated",
"minDistance" => 0,
"maxDistance" => 6000,
"includeLocs" => "dist.location",
"spherical" => true,
]
]
]);
});
Inserts, updates and deletes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Inserting, updating and deleting records works just like the original Eloquent.
Please check `Laravel Docs' Eloquent section <https://laravel.com/docs/6.x/eloquent>`__.
Here, only the MongoDB-specific operations are specified.
MongoDB specific operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~
**Raw Expressions**
These expressions will be injected directly into the query.
.. code-block:: php
User::whereRaw([
'age' => ['$gt' => 30, '$lt' => 40],
])->get();
User::whereRaw([
'$where' => '/.*123.*/.test(this.field)',
])->get();
User::whereRaw([
'$where' => '/.*123.*/.test(this["hyphenated-field"])',
])->get();
You can also perform raw expressions on the internal MongoCollection object.
If this is executed on the model class, it will return a collection of models.
If this is executed on the query builder, it will return the original response.
**Cursor timeout**
To prevent ``MongoCursorTimeout`` exceptions, you can manually set a timeout
value that will be applied to the cursor:
.. code-block:: php
DB::collection('users')->timeout(-1)->get();
**Upsert**
Update or insert a document. Other options for the update method can be
passed directly to the native update method.
.. code-block:: php
// Query Builder
DB::collection('users')
->where('name', 'John')
->update($data, ['upsert' => true]);
// Eloquent
$user->update($data, ['upsert' => true]);
**Projections**
You can apply projections to your queries using the ``project`` method.
.. code-block:: php
DB::collection('items')
->project(['tags' => ['$slice' => 1]])
->get();
DB::collection('items')
->project(['tags' => ['$slice' => [3, 7]]])
->get();
**Projections with Pagination**
.. code-block:: php
$limit = 25;
$projections = ['id', 'name'];
DB::collection('items')
->paginate($limit, $projections);
**Push**
Add items to an array.
.. code-block:: php
DB::collection('users')
->where('name', 'John')
->push('items', 'boots');
$user->push('items', 'boots');
.. code-block:: php
DB::collection('users')
->where('name', 'John')
->push('messages', [
'from' => 'Jane Doe',
'message' => 'Hi John',
]);
$user->push('messages', [
'from' => 'Jane Doe',
'message' => 'Hi John',
]);
If you **DON'T** want duplicate items, set the third parameter to ``true``:
.. code-block:: php
DB::collection('users')
->where('name', 'John')
->push('items', 'boots', true);
$user->push('items', 'boots', true);
**Pull**
Remove an item from an array.
.. code-block:: php
DB::collection('users')
->where('name', 'John')
->pull('items', 'boots');
$user->pull('items', 'boots');
.. code-block:: php
DB::collection('users')
->where('name', 'John')
->pull('messages', [
'from' => 'Jane Doe',
'message' => 'Hi John',
]);
$user->pull('messages', [
'from' => 'Jane Doe',
'message' => 'Hi John',
]);
**Unset**
Remove one or more fields from a document.
.. code-block:: php
DB::collection('users')
->where('name', 'John')
->unset('note');
$user->unset('note');
$user->save();
Using the native ``unset`` on models will work as well:
.. code-block:: php
unset($user['note']);
unset($user->node);