-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathmongo.ex
2018 lines (1692 loc) · 65.2 KB
/
mongo.ex
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Mongo do
@moduledoc """
The main entry point for doing queries. All functions take a topology to
run the query on.
## Generic options
All operations take these options.
* `:timeout` - The maximum time that the caller is allowed the to hold the
connection’s state (ignored when using a run/transaction connection,
default: `15_000`)
* `:checkout_timeout` - The maximum time for checking out a new session and connection (default: `60_000`).
When the connection pool exhausted then the function call times out after :checkout_timeout.
* `:pool` - The pooling behaviour module to use, this option is required
unless the default `DBConnection` pool is used
* `:pool_timeout` - The maximum time to wait for a reply when making a
synchronous call to the pool (default: `5_000`)
* `:queue` - Whether to block waiting in an internal queue for the
connection's state (boolean, default: `true`)
* `:log` - A function to log information about a call, either
a 1-arity fun, `{module, function, args}` with `DBConnection.LogEntry.t`
prepended to `args` or `nil`. See `DBConnection.LogEntry` (default: `nil`)
* `:database` - the database to run the operation on
* `:connect_timeout` - maximum timeout for connect (default: `5_000`)
## Read options
All read operations that returns a cursor take the following options
for controlling the behaviour of the cursor.
* `:batch_size` - Number of documents to fetch in each batch
* `:limit` - Maximum number of documents to fetch with the cursor
* `:read_preference` - specifies the rules for selecting a server to query
## Write options
All write operations take the following options for controlling the
write concern.
* `:w` - The number of servers to replicate to before returning from write
operators, a 0 value will return immediately, :majority will wait until
the operation propagates to a majority of members in the replica set
(Default: 1)
* `:j` If true, the write operation will only return after it has been
committed to journal - (Default: false)
* `:wtimeout` - If the write concern is not satisfied in the specified
interval, the operation returns an error
"""
import Keywords
import Mongo.Utils
import Mongo.WriteConcern
require Logger
use Mongo.Messages
import Mongo.Session, only: [in_read_session: 3, in_write_session: 3]
alias Mongo.Query
alias Mongo.Topology
alias Mongo.UrlParser
alias Mongo.Session
alias Mongo.Events
alias Mongo.Events.CommandSucceededEvent
alias Mongo.Events.CommandFailedEvent
alias Mongo.Error
@retry_timeout_seconds 120
@type conn :: DbConnection.Conn
@type collection :: String.t()
@type cursor :: Mongo.Cursor.t()
@type result(t) :: {:ok, t} | {:error, Mongo.Error.t()} | {:error, Mongo.WriteError.t()}
@type result!(t) :: t
defmacrop bangify(result) do
quote do
case unquote(result) do
{:ok, value} -> value
{:error, error} -> raise error
end
end
end
@doc """
Start and link to a database connection process.
### Options
* `:database` - The database to use (required)
* `:hostname` - The host to connect to (require)
* `:port` - The port to connect to your server (default: 27017)
* `:url` - A mongo connection url. Can be used in place of `:hostname` and `:database` (optional)
* `:socket_dir` - Connect to MongoDB via UNIX sockets in the given directory.
The socket name is derived based on the port. This is the preferred method
for configuring sockets and it takes precedence over the hostname. If you
are connecting to a socket outside of the MongoDB convection, use
`:socket` instead.
* `:socket` - Connect to MongoDB via UNIX sockets in the given path.
This option takes precedence over `:hostname` and `:socket_dir`.
* `:database` (optional)
* `:seeds` - A list of host names in the cluster. Can be used in place of
`:hostname` (optional)
* `:username` - The User to connect with (optional)
* `:password` - The password to connect with (optional)
* `:auth_source` - The database to authenticate against
* `:appname` - The name of the application used the driver for the MongoDB-Handshake
* `:set_name` - The name of the replica set to connect to (required if
connecting to a replica set)
* `:type` - a hint of the topology type. See `t:initial_type/0` for
valid values (default: `:unknown`)
* `:idle` - The idle strategy, `:passive` to avoid checkin when idle and
`:active` to checking when idle (default: `:passive`)
* `:idle_timeout` - The idle timeout to ping the database (default: `1_000`)
* `:connect_timeout` - The maximum timeout for the initial connection
(default: `5_000`)
* `:backoff_min` - The minimum backoff interval (default: `1_000`)
* `:backoff_max` - The maximum backoff interval (default: `30_000`)
* `:backoff_type` - The backoff strategy, `:stop` for no backoff and to
stop, `:exp` of exponential, `:rand` for random and `:ran_exp` for random
exponential (default: `:rand_exp`)
* `:after_connect` - A function to run on connect use `run/3`. Either a
1-arity fun, `{module, function, args}` with `DBConnection.t`, prepended
to `args` or `nil` (default: `nil`)
* `:auth_mechanism` - options for the mongo authentication mechanism,
currently only supports `:x509` atom as a value
* `:ssl` - Set to `true` if ssl should be used (default: `false`)
* `:ssl_opts` - A list of ssl options, see the ssl docs
### Error Reasons
* `:single_topology_multiple_hosts` - A topology of `:single` was set
but multiple hosts were given
* `:set_name_bad_topology` - A `:set_name` was given but the topology was
set to something other than `:replica_set_no_primary` or `:single`
"""
@spec start_link(Keyword.t()) :: {:ok, pid} | {:error, Mongo.Error.t() | atom}
def start_link(opts) do
opts
|> UrlParser.parse_url()
|> Topology.start_link()
end
def child_spec(opts) do
%{id: Mongo, start: {Mongo, :start_link, [opts]}}
end
@doc """
Convenient function for running multiple write commands in a transaction.
In case of `TransientTransactionError` or `UnknownTransactionCommitResult` the function will retry the whole transaction or
the commit of the transaction. You can specify a timeout (`:transaction_retry_timeout_s`) to limit the time of repeating.
The default value is 120 seconds. If you don't wait so long, you call `with_transaction` with the
option `transaction_retry_timeout_s: 10`. In this case after 10 seconds of retrying, the function will return
an error.
## Example
{:ok, ids} = Mongo.transaction(top, fn ->
{:ok, %InsertOneResult{:inserted_id => id1}} = Mongo.insert_one(top, "dogs", %{name: "Greta"})
{:ok, %InsertOneResult{:inserted_id => id2}} = Mongo.insert_one(top, "dogs", %{name: "Waldo"})
{:ok, %InsertOneResult{:inserted_id => id3}} = Mongo.insert_one(top, "dogs", %{name: "Tom"})
{:ok, [id1, id2, id3]}
end, transaction_retry_timeout_s: 10)
If transaction/3 is called inside another transaction, the function is simply executed, without wrapping the new transaction call in any way.
If there is an error in the inner transaction and the error is rescued, or the inner transaction is aborted (abort_transaction/1),
the whole outer transaction is aborted, guaranteeing nothing will be committed.
"""
@spec transaction(GenServer.server(), function) :: {:ok, any()} | :error | {:error, term}
def transaction(topology_pid, fun, opts \\ []) do
:session
|> Process.get()
|> do_transaction(topology_pid, fun, opts)
end
defp do_transaction(nil, topology_pid, fun, opts) do
## try catch
with {:ok, session} <- Session.start_session(topology_pid, :write, opts) do
Process.put(:session, session)
try do
run_in_transaction(topology_pid, session, fun, DateTime.utc_now(), opts)
rescue
error ->
{:error, error}
after
Session.end_session(topology_pid, session)
Process.delete(:session)
end
end
end
defp do_transaction(_session, _topology_pid, fun, _opts) when is_function(fun, 0) do
fun.()
end
defp do_transaction(_session, _topology_pid, fun, opts) when is_function(fun, 1) do
fun.(opts)
end
defp run_in_transaction(topology_pid, session, fun, start_time, opts) do
Session.start_transaction(session)
case run_function(fun, Keyword.merge(opts, session: session)) do
:ok ->
handle_commit(session, start_time)
{:ok, result} ->
handle_commit(session, start_time, result)
{:error, error} ->
## check in case of an error while processing transaction
Session.abort_transaction(session)
timeout = opts[:transaction_retry_timeout_s] || @retry_timeout_seconds
case Error.has_label(error, "TransientTransactionError") && DateTime.diff(DateTime.utc_now(), start_time, :second) < timeout do
true ->
run_in_transaction(topology_pid, session, fun, start_time, opts)
false ->
{:error, error}
end
:error ->
Session.abort_transaction(session)
:error
other ->
## everything else is an error
Session.abort_transaction(session)
{:error, other}
end
end
##
# calling the function and wrapping it to catch exceptions
#
defp run_function(fun, _opts) when is_function(fun, 0) do
try do
fun.()
rescue
reason -> {:error, reason}
end
end
defp run_function(fun, opts) when is_function(fun, 1) do
try do
fun.(opts)
rescue
reason -> {:error, reason}
end
end
defp handle_commit(session, start_time) do
case Session.commit_transaction(session, start_time) do
## everything is okay
:ok ->
:ok
error ->
## the rest is an error
Session.abort_transaction(session)
error
end
end
defp handle_commit(session, start_time, result) do
case Session.commit_transaction(session, start_time) do
## everything is okay
:ok ->
{:ok, result}
error ->
## the rest is an error
Session.abort_transaction(session)
error
end
end
def abort_transaction(reason) do
:session
|> Process.get()
|> abort_transaction(reason)
end
def abort_transaction(nil, reason) do
raise Mongo.Error.exception("Aborting transaction (#{inspect(reason)}) is not allowed, because there is no active transaction!")
end
def abort_transaction(_session, reason) do
raise Mongo.Error.exception("Aborting transaction, reason #{inspect(reason)}")
end
@doc """
Convenient function to execute write and read operation with a causal consistency session.
With causally consistent sessions, MongoDB executes causal operations in an order that respect their
causal relationships, and clients observe results that are consistent with the causal relationships.
## Example
{:ok, 0} = Mongo.causal_consistency(top, fn ->
Mongo.delete_many(top, "dogs", %{name: "Greta"}, w: :majority)
Mongo.count(top, "dogs", %{name: "Greta"}, read_concern: %{level: :majority})
end)
The function creates a causal consistency session and stores it in the process dictionary under
the key `:session`. But you need to specify the write and read concerns for each operation to
`:majority`
"""
@spec transaction(GenServer.server(), function) :: {:ok, any()} | :error | {:error, term}
def causal_consistency(topology_pid, fun, opts \\ []) do
:session
|> Process.get()
|> do_causal_consistency(topology_pid, fun, opts)
end
defp do_causal_consistency(nil, topology_pid, fun, opts) do
opts = Keyword.merge(opts, causal_consistency: true)
with {:ok, session} <- Session.start_session(topology_pid, :write, opts) do
Process.put(:session, session)
try do
run_function(fun, Keyword.merge(opts, session: session))
rescue
error ->
{:error, error}
after
Session.end_session(topology_pid, session)
Process.delete(:session)
end
end
end
defp do_causal_consistency(_session, _topology_pid, fun, _opts) when is_function(fun, 0) do
fun.()
end
defp do_causal_consistency(_session, _topology_pid, fun, opts) when is_function(fun, 1) do
fun.(opts)
end
@doc """
Creates a change stream cursor on collections.
`on_resume_token` is function that takes the new resume token, if it changed.
## Options
* `:full_document` -
* `:max_time` - Specifies a time limit in milliseconds. This option is used on `getMore` commands
* `:batch_size` - Specifies the number of maximum number of documents to
return (default: 1)
* `:resume_after` - Specifies the logical starting point for the new change stream.
* `:start_at_operation_time` - The change stream will only provide changes that occurred at or after the specified timestamp (since 4.0)
* `:start_after` - Similar to `resumeAfter`, this option takes a resume token and starts a new change stream
returning the first notification after the token. This will allow users to watch collections that have been dropped and recreated
or newly renamed collections without missing any notifications. (since 4.0.7)
"""
@spec watch_collection(GenServer.server(), collection | 1, [BSON.document()], fun | nil, Keyword.t()) ::
cursor
def watch_collection(topology_pid, coll, pipeline, on_resume_token \\ nil, opts \\ []) do
stream_opts =
%{
fullDocument: opts[:full_document] || "default",
resumeAfter: opts[:resume_after],
startAtOperationTime: opts[:start_at_operation_time],
startAfter: opts[:start_after]
}
|> filter_nils()
cmd =
[
aggregate: coll,
pipeline: [%{"$changeStream" => stream_opts} | pipeline],
explain: opts[:explain],
allowDiskUse: opts[:allow_disk_use],
collation: opts[:collation],
maxTimeMS: opts[:max_time],
cursor: filter_nils(%{batchSize: opts[:batch_size]}),
bypassDocumentValidation: opts[:bypass_document_validation],
hint: opts[:hint],
comment: opts[:comment],
readConcern: opts[:read_concern]
]
|> filter_nils()
opts =
Keyword.drop(
opts,
~w(full_document resume_after start_at_operation_time start_after explain allow_disk_use collation bypass_document_validation hint comment read_concern)a
)
on_resume_token = on_resume_token || fn _token -> nil end
change_stream_cursor(topology_pid, cmd, on_resume_token, opts)
end
@doc """
Creates a change stream cursor all collections of the database.
`on_resume_token` is function that takes the new resume token, if it changed.
## Options
* `:full_document` -
* `:max_time` - Specifies a time limit in milliseconds. This option is used on `getMore` commands
* `:batch_size` - Specifies the number of maximum number of documents to
return (default: 1)
* `:resume_after` - Specifies the logical starting point for the new change stream.
* `:start_at_operation_time` - The change stream will only provide changes that occurred at or after the specified timestamp (since 4.0)
* `:start_after` - Similar to `resumeAfter`, this option takes a resume token and starts a new change stream
returning the first notification after the token. This will allow users to watch collections that have been dropped and recreated
or newly renamed collections without missing any notifications. (since 4.0.7)
"""
@spec watch_db(GenServer.server(), [BSON.document()], fun | nil, Keyword.t()) :: cursor
def watch_db(topology_pid, pipeline, on_resume_token \\ nil, opts \\ []) do
watch_collection(topology_pid, 1, pipeline, on_resume_token, opts)
end
@doc """
Performs aggregation operation using the aggregation pipeline and returns a Mongo.Stream.
It should be noted that code that uses the paginated query results without engaging Mongo.Streams Enumerable behavior
can result in the sessions hanging around and causing resource exhaustion.
Example:
# Results in an open session
%Mongo.Stream{docs: docs} = Mongo.aggregate(@topology, collection, pipeline, opts)
docs |> Enum.map(fn elem -> elem end)
# Results in a closed session via the Enumerable protocol
Mongo.aggregate(@topology, collection, pipeline, opts)
|> Enum.map(fn elem -> elem end)
For all options see [Options](https://docs.mongodb.com/manual/reference/command/aggregate/#aggregate)
"""
@spec aggregate(GenServer.server(), collection, [BSON.document()], Keyword.t()) :: cursor
def aggregate(topology_pid, coll, pipeline, opts \\ []) do
cmd =
[
aggregate: coll,
pipeline: pipeline,
explain: opts[:explain],
allowDiskUse: opts[:allow_disk_use],
collation: opts[:collation],
maxTimeMS: opts[:max_time],
cursor: filter_nils(%{batchSize: opts[:batch_size]}),
bypassDocumentValidation: opts[:bypass_document_validation],
hint: opts[:hint],
comment: opts[:comment],
readConcern: opts[:read_concern]
]
|> filter_nils()
opts =
opts
|> Keyword.drop(~w(explain allow_disk_use collation bypass_document_validation hint comment read_concern)a)
|> Keyword.put_new(:compression, true)
get_stream(topology_pid, cmd, opts)
end
@doc """
Finds a document and updates it (using atomic modifiers).
## Options
* `:bypass_document_validation` - Allows the write to opt-out of document
level validation
* `:max_time` - The maximum amount of time to allow the query to run (in MS)
* `:projection` - Limits the fields to return for all matching documents.
* `:return_document` - Returns the replaced or inserted document rather than
the original. Values are :before or :after. (default is :before)
* `:sort` - Determines which document the operation modifies if the query
selects multiple documents.
* `:upsert` - Create a document if no document matches the query or updates
the document.
* `:collation` - Optionally specifies a collation to use in MongoDB 3.4 and
"""
@spec find_one_and_update(
GenServer.server(),
collection,
BSON.document(),
BSON.document(),
Keyword.t()
) :: result(Mongo.FindAndModifyResult.t())
def find_one_and_update(topology_pid, coll, filter, update, opts \\ []) do
_ = modifier_docs(update, :update)
cmd =
[
findAndModify: coll,
query: filter,
sort: opts[:sort],
update: update,
new: should_return_new(opts[:return_document]),
fields: opts[:projection],
upsert: opts[:upsert],
bypassDocumentValidation: opts[:bypass_document_validation],
writeConcern: write_concern(opts),
maxTimeMS: opts[:max_time],
collation: opts[:collation],
comment: opts[:comment],
arrayFilters: opts[:array_filters]
]
|> filter_nils()
opts =
opts
|> Keyword.drop(~w(bypass_document_validation max_time projection return_document sort upsert collation w j wtimeout)a)
|> Keyword.put_new(:compression, true)
with {:ok, doc} <- issue_command(topology_pid, cmd, :write, opts) do
{:ok,
%Mongo.FindAndModifyResult{
value: doc["value"],
matched_count: doc["lastErrorObject"]["n"],
updated_existing: doc["lastErrorObject"]["updatedExisting"],
upserted_id: doc["lastErrorObject"]["upserted"]
}}
end
end
@doc """
Finds a document and replaces it.
## Options
* `:bypass_document_validation` - Allows the write to opt-out of document
level validation
* `:max_time` - The maximum amount of time to allow the query to run (in MS)
* `:projection` - Limits the fields to return for all matching documents.
* `:return_document` - Returns the replaced or inserted document rather than
the original. Values are :before or :after. (default is :before)
* `:sort` - Determines which document the operation modifies if the query
selects multiple documents.
* `:upsert` - Create a document if no document matches the query or updates
the document.
* `:collation` - Optionally specifies a collation to use in MongoDB 3.4 and
higher.
"""
@spec find_one_and_replace(
GenServer.server(),
collection,
BSON.document(),
BSON.document(),
Keyword.t()
) :: result(Mongo.FindAndModifyResult.t())
def find_one_and_replace(topology_pid, coll, filter, replacement, opts \\ []) do
_ = modifier_docs(replacement, :replace)
write_concern = write_concern(opts)
cmd =
[
findAndModify: coll,
query: filter,
update: replacement,
bypassDocumentValidation: opts[:bypass_document_validation],
maxTimeMS: opts[:max_time],
fields: opts[:projection],
new: should_return_new(opts[:return_document]),
sort: opts[:sort],
upsert: opts[:upsert],
collation: opts[:collation],
writeConcern: write_concern
]
|> filter_nils()
opts =
opts
|> Keyword.drop(~w(bypass_document_validation max_time projection return_document sort upsert collation)a)
|> Keyword.put_new(:compression, true)
with {:ok, doc} <- issue_command(topology_pid, cmd, :write, opts) do
{:ok,
%Mongo.FindAndModifyResult{
value: doc["value"],
matched_count: doc["lastErrorObject"]["n"],
updated_existing: doc["lastErrorObject"]["updatedExisting"],
upserted_id: doc["lastErrorObject"]["upserted"]
}}
end
end
defp should_return_new(:after), do: true
defp should_return_new(:before), do: false
defp should_return_new(_), do: false
@doc """
Finds a document and deletes it.
## Options
* `:max_time` - The maximum amount of time to allow the query to run (in MS)
* `:projection` - Limits the fields to return for all matching documents.
* `:sort` - Determines which document the operation modifies if the query selects multiple documents.
* `:collation` - Optionally specifies a collation to use in MongoDB 3.4 and higher.
"""
@spec find_one_and_delete(GenServer.server(), collection, BSON.document(), Keyword.t()) ::
result(BSON.document())
def find_one_and_delete(topology_pid, coll, filter, opts \\ []) do
write_concern = write_concern(opts)
cmd =
[
findAndModify: coll,
query: filter,
remove: true,
maxTimeMS: opts[:max_time],
fields: opts[:projection],
sort: opts[:sort],
collation: opts[:collation],
writeConcern: write_concern
]
|> filter_nils()
opts =
opts
|> Keyword.drop(~w(max_time projection sort collation)a)
|> Keyword.put_new(:compression, true)
with {:ok, doc} <- issue_command(topology_pid, cmd, :write, opts), do: {:ok, doc["value"]}
end
@doc false
@spec count(GenServer.server(), collection, BSON.document(), Keyword.t()) :: result(non_neg_integer)
def count(topology_pid, coll, filter, opts \\ []) do
cmd =
[
count: coll,
query: filter,
limit: opts[:limit],
skip: opts[:skip],
hint: opts[:hint],
collation: opts[:collation]
]
|> filter_nils()
opts =
opts
|> Keyword.drop(~w(limit skip hint collation)a)
|> Keyword.put_new(:compression, true)
with {:ok, doc} <- issue_command(topology_pid, cmd, :read, opts) do
{:ok, trunc(doc["n"])}
end
end
@doc false
@spec count!(GenServer.server(), collection, BSON.document(), Keyword.t()) ::
result!(non_neg_integer)
def count!(topology_pid, coll, filter, opts \\ []) do
bangify(count(topology_pid, coll, filter, opts))
end
@doc """
Returns the count of documents that would match a find/4 query.
## Options
* `:limit` - Maximum number of documents to fetch with the cursor
* `:skip` - Number of documents to skip before returning the first
"""
@spec count_documents(GenServer.server(), collection, BSON.document(), Keyword.t()) ::
result(non_neg_integer)
def count_documents(topology_pid, coll, filter, opts \\ []) do
pipeline =
[
"$match": filter,
"$skip": opts[:skip],
"$limit": opts[:limit],
"$group": %{"_id" => nil, "n" => %{"$sum" => 1}}
]
|> filter_nils()
|> Enum.map(&List.wrap/1)
with %Mongo.Stream{} = cursor <- Mongo.aggregate(topology_pid, coll, pipeline, opts),
documents <- Enum.to_list(cursor) do
case documents do
[%{"n" => count}] -> {:ok, count}
[] -> {:ok, 0}
end
else
_ -> {:error, Mongo.Error.exception("Failed to count")}
end
end
@doc """
Similar to `count_documents/4` but unwraps the result and raises on error.
"""
@spec count_documents!(GenServer.server(), collection, BSON.document(), Keyword.t()) ::
result!(non_neg_integer)
def count_documents!(topology_pid, coll, filter, opts \\ []) do
bangify(count_documents(topology_pid, coll, filter, opts))
end
@doc """
Estimate the number of documents in a collection using collection metadata.
"""
@spec estimated_document_count(GenServer.server(), collection, Keyword.t()) ::
result(non_neg_integer)
def estimated_document_count(topology_pid, coll, opts) do
opts = Keyword.drop(opts, [:skip, :limit, :hint, :collation])
count(topology_pid, coll, %{}, opts)
end
@doc """
Similar to `estimated_document_count/3` but unwraps the result and raises on
error.
"""
@spec estimated_document_count!(GenServer.server(), collection, Keyword.t()) ::
result!(non_neg_integer)
def estimated_document_count!(topology_pid, coll, opts) do
bangify(estimated_document_count(topology_pid, coll, opts))
end
@doc """
Finds the distinct values for a specified field across a collection.
## Options
* `:max_time` - Specifies a time limit in milliseconds
* `:collation` - Optionally specifies a collation to use in MongoDB 3.4 and
"""
@spec distinct(GenServer.server(), collection, String.t() | atom, BSON.document(), Keyword.t()) ::
result([BSON.t()])
def distinct(topology_pid, coll, field, filter, opts \\ []) do
cmd =
[
distinct: coll,
key: field,
query: filter,
collation: opts[:collation],
maxTimeMS: opts[:max_time]
]
|> filter_nils()
opts =
opts
|> Keyword.drop(~w(max_time)a)
|> Keyword.put_new(:compression, true)
with {:ok, doc} <- issue_command(topology_pid, cmd, :read, opts), do: {:ok, doc["values"]}
end
@doc """
Similar to `distinct/5` but unwraps the result and raises on error.
"""
@spec distinct!(GenServer.server(), collection, String.t() | atom, BSON.document(), Keyword.t()) ::
result!([BSON.t()])
def distinct!(topology_pid, coll, field, filter, opts \\ []) do
bangify(distinct(topology_pid, coll, field, filter, opts))
end
@doc """
Selects documents in a collection and returns a cursor for the selected
documents.
For all options see [Options](https://docs.mongodb.com/manual/reference/command/find/#dbcmd.find)
Use the underscore style, for example to set the option `singleBatch` use `single_batch`. Another example:
Mongo.find(top, "jobs", %{}, batch_size: 2)
"""
@spec find(GenServer.server(), collection, BSON.document(), Keyword.t()) ::
cursor | {:error, term()}
def find(topology_pid, coll, filter, opts \\ []) do
filter =
case normalize_doc(filter) do
[] -> nil
other -> other
end
cmd = [
find: coll,
filter: filter,
limit: opts[:limit],
hint: opts[:hint],
singleBatch: opts[:single_batch],
readConcern: opts[:read_concern],
max: opts[:max],
min: opts[:min],
collation: opts[:collation],
returnKey: opts[:return_key],
showRecordId: opts[:show_record_id],
tailable: opts[:tailable],
oplogReplay: opts[:oplog_replay],
noCursorTimeout: opts[:no_cursor_timeout],
awaitData: opts[:await_data],
batchSize: opts[:batch_size],
projection: opts[:projection],
comment: opts[:comment],
maxTimeMS: opts[:max_time],
skip: opts[:skip],
sort: opts[:sort]
]
cmd = filter_nils(cmd)
drop = ~w(limit hint single_batch read_concern max min collation return_key show_record_id tailable no_cursor_timeout await_data projection comment skip sort)a
opts =
opts
|> Keyword.drop(drop)
|> Keyword.put_new(:compression, true)
try do
get_stream(topology_pid, cmd, opts)
rescue
error -> {:error, error}
end
end
@doc """
Selects a single document in a collection and returns either a document
or nil.
If multiple documents satisfy the query, this method returns the first document
according to the natural order which reflects the order of documents on the disk.
For all options see [Options](https://docs.mongodb.com/manual/reference/command/find/#dbcmd.find)
Use the underscore style, for example to set the option `readConcern` use `read_concern`. Another example:
Mongo.find_one(top, "jobs", %{}, read_concern: %{level: "local"})
"""
@spec find_one(GenServer.server(), collection, BSON.document(), Keyword.t()) ::
BSON.document() | nil | {:error, any}
def find_one(topology_pid, coll, filter, opts \\ []) do
opts =
opts
|> Keyword.put(:limit, 1)
|> Keyword.put(:batch_size, 1)
try do
case find(topology_pid, coll, filter, opts) do
{:error, error} -> {:error, error}
other -> Enum.at(other, 0)
end
rescue
error -> {:error, error}
end
end
@doc """
Insert a single document into the collection.
If the document is missing the `_id` field or it is `nil`, an ObjectId
will be generated, inserted into the document, and returned in the result struct.
## Examples
Mongo.insert_one(pid, "users", %{first_name: "John", last_name: "Smith"})
{:ok, session} = Session.start_session(pid)
Session.start_transaction(session)
Mongo.insert_one(pid, "users", %{first_name: "John", last_name: "Smith"}, session: session)
Session.commit_transaction(session)
Session.end_session(pid)
"""
@spec insert_one(GenServer.server(), collection, BSON.document(), Keyword.t()) ::
result(Mongo.InsertOneResult.t())
def insert_one(topology_pid, coll, doc, opts \\ []) do
assert_single_doc!(doc)
{[id], [doc]} = assign_ids([doc])
write_concern = write_concern(opts)
cmd =
[
insert: coll,
documents: [doc],
ordered: Keyword.get(opts, :ordered),
writeConcern: write_concern,
bypassDocumentValidation: Keyword.get(opts, :bypass_document_validation)
]
|> filter_nils()
with {:ok, doc} <- issue_command(topology_pid, cmd, :write, Keyword.put_new(opts, :compression, true)) do
case doc do
%{"writeErrors" => _} ->
{:error, %Mongo.WriteError{n: doc["n"], ok: doc["ok"], write_errors: doc["writeErrors"]}}
_ ->
case acknowledged?(write_concern) do
false -> {:ok, %Mongo.InsertOneResult{acknowledged: false}}
true -> {:ok, %Mongo.InsertOneResult{inserted_id: id}}
end
end
end
end
@doc """
Similar to `insert_one/4` but unwraps the result and raises on error.
"""
@spec insert_one!(GenServer.server(), collection, BSON.document(), Keyword.t()) ::
result!(Mongo.InsertOneResult.t())
def insert_one!(topology_pid, coll, doc, opts \\ []) do
bangify(insert_one(topology_pid, coll, doc, opts))
end
@doc """
Insert multiple documents into the collection.
If any of the documents is missing the `_id` field or it is `nil`, an ObjectId will be generated, and inserted into the document.
Ids of all documents will be returned in the result struct.
## Options
For more information about options see [Options](https://docs.mongodb.com/manual/reference/command/insert/)
## Examples
Mongo.insert_many(pid, "users", [%{first_name: "John", last_name: "Smith"}, %{first_name: "Jane", last_name: "Doe"}])
"""
@spec insert_many(GenServer.server(), collection, [BSON.document()], Keyword.t()) ::
result(Mongo.InsertManyResult.t())
def insert_many(topology_pid, coll, docs, opts \\ []) do
assert_many_docs!(docs)
{ids, docs} = assign_ids(docs)
write_concern = write_concern(opts)
cmd =
[
insert: coll,
documents: docs,
ordered: Keyword.get(opts, :ordered),
writeConcern: write_concern,
bypassDocumentValidation: Keyword.get(opts, :bypass_document_validation)
]
|> filter_nils()
case issue_command(topology_pid, cmd, :write, Keyword.put_new(opts, :compression, true)) do
{:ok, %{"writeErrors" => _} = doc} ->
{:error, %Mongo.WriteError{n: doc["n"], ok: doc["ok"], write_errors: doc["writeErrors"]}}
{:ok, _doc} ->
case acknowledged?(write_concern) do
false -> {:ok, %Mongo.InsertManyResult{acknowledged: false}}
true -> {:ok, %Mongo.InsertManyResult{inserted_ids: ids}}
end
_ ->
{:error, Mongo.Error.exception("Failed to insert many")}
end
end
@doc """
Similar to `insert_many/4` but unwraps the result and raises on error.
"""
@spec insert_many!(GenServer.server(), collection, [BSON.document()], Keyword.t()) ::
result!(Mongo.InsertManyResult.t())
def insert_many!(topology_pid, coll, docs, opts \\ []) do
bangify(insert_many(topology_pid, coll, docs, opts))
end
@doc """
Remove a document matching the filter from the collection.
"""
@spec delete_one(GenServer.server(), collection, BSON.document(), Keyword.t()) ::
result(Mongo.DeleteResult.t())
def delete_one(topology_pid, coll, filter, opts \\ []) do
delete_documents(topology_pid, coll, filter, 1, opts)
end
@doc """
Similar to `delete_one/4` but unwraps the result and raises on error.
"""
@spec delete_one!(GenServer.server(), collection, BSON.document(), Keyword.t()) ::
result!(Mongo.DeleteResult.t())
def delete_one!(topology_pid, coll, filter, opts \\ []) do
bangify(delete_one(topology_pid, coll, filter, opts))
end
@doc """
Remove all documents matching the filter from the collection.
"""
@spec delete_many(GenServer.server(), collection, BSON.document(), Keyword.t()) ::
result(Mongo.DeleteResult.t())
def delete_many(topology_pid, coll, filter, opts \\ []) do
delete_documents(topology_pid, coll, filter, 0, opts)
end
##
# This is the implementation of the delete command for
# delete_one and delete_many
#
defp delete_documents(topology_pid, coll, filter, limit, opts) do
# see https://docs.mongodb.com/manual/reference/command/delete/#dbcmd.delete
write_concern = write_concern(opts)
filter =
%{
q: filter,
limit: limit,
collation: Keyword.get(opts, :collation)