-
Notifications
You must be signed in to change notification settings - Fork 281
/
Copy pathcollection.d
1550 lines (1317 loc) · 47.8 KB
/
collection.d
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
/**
MongoCollection class
Copyright: © 2012-2016 Sönke Ludwig
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
Authors: Sönke Ludwig
*/
module vibe.db.mongo.collection;
public import vibe.db.mongo.cursor;
public import vibe.db.mongo.connection;
public import vibe.db.mongo.flags;
public import vibe.db.mongo.impl.index;
public import vibe.db.mongo.impl.crud;
import vibe.core.log;
import vibe.db.mongo.client;
import core.time;
import std.algorithm : among, countUntil, find, findSplit;
import std.array;
import std.conv;
import std.exception;
import std.meta : AliasSeq;
import std.string;
import std.traits : FieldNameTuple;
import std.typecons : Nullable, tuple, Tuple;
/**
Represents a single collection inside a MongoDB.
All methods take arbitrary types for Bson arguments. serializeToBson() is implicitly called on
them before they are send to the database. The following example shows some possible ways
to specify objects.
*/
struct MongoCollection {
private {
MongoClient m_client;
MongoDatabase m_db;
string m_name;
string m_fullPath;
}
this(MongoClient client, string fullPath)
@safe {
assert(client !is null);
m_client = client;
auto dotidx = fullPath.indexOf('.');
assert(dotidx > 0, "The collection name passed to MongoCollection must be of the form \"dbname.collectionname\".");
m_fullPath = fullPath;
m_db = m_client.getDatabase(fullPath[0 .. dotidx]);
m_name = fullPath[dotidx+1 .. $];
}
this(ref MongoDatabase db, string name)
@safe {
assert(db.client !is null);
m_client = db.client;
m_fullPath = db.name ~ "." ~ name;
m_db = db;
m_name = name;
}
/**
Returns: Root database to which this collection belongs.
*/
@property MongoDatabase database() @safe { return m_db; }
/**
Returns: Name of this collection (excluding the database name).
*/
@property string name() const @safe { return m_name; }
/**
Performs an update operation on documents matching 'selector', updating them with 'update'.
Throws: Exception if a DB communication error occurred.
See_Also: $(LINK http://www.mongodb.org/display/DOCS/Updating)
*/
deprecated("Use `replaceOne`, `updateOne` or `updateMany` taking `UpdateOptions` instead, this method breaks in MongoDB 5.1 and onwards.")
void update(T, U)(T selector, U update, UpdateFlags flags = UpdateFlags.None)
{
assert(m_client !is null, "Updating uninitialized MongoCollection.");
auto conn = m_client.lockConnection();
ubyte[256] selector_buf = void, update_buf = void;
conn.update(m_fullPath, flags, serializeToBson(selector, selector_buf), serializeToBson(update, update_buf));
}
/**
Inserts new documents into the collection.
Note that if the `_id` field of the document(s) is not set, typically
using `BsonObjectID.generate()`, the server will generate IDs
automatically. If you need to know the IDs of the inserted documents,
you need to generate them locally.
Throws: Exception if a DB communication error occurred.
See_Also: $(LINK http://www.mongodb.org/display/DOCS/Inserting)
*/
deprecated("Use `insertOne` or `insertMany`, this method breaks in MongoDB 5.1 and onwards.")
void insert(T)(T document_or_documents, InsertFlags flags = InsertFlags.None)
{
assert(m_client !is null, "Inserting into uninitialized MongoCollection.");
auto conn = m_client.lockConnection();
Bson[] docs;
Bson bdocs = () @trusted { return serializeToBson(document_or_documents); } ();
if( bdocs.type == Bson.Type.Array ) docs = cast(Bson[])bdocs;
else docs = () @trusted { return (&bdocs)[0 .. 1]; } ();
conn.insert(m_fullPath, flags, docs);
}
/**
Inserts the provided document(s). If a document is missing an identifier,
one is generated automatically by vibe.d.
See_Also: $(LINK https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne/#mongodb-method-db.collection.insertOne)
Standards: $(LINK https://www.mongodb.com/docs/manual/reference/command/insert/)
*/
InsertOneResult insertOne(T)(T document, InsertOneOptions options = InsertOneOptions.init)
{
assert(m_client !is null, "Querying uninitialized MongoCollection.");
Bson cmd = Bson.emptyObject; // empty object because order is important
cmd["insert"] = Bson(m_name);
auto doc = serializeToBson(document);
enforce(doc.type == Bson.Type.object, "Can only insert objects into collections");
InsertOneResult res;
if ("_id" !in doc.get!(Bson[string]))
{
doc["_id"] = Bson(res.insertedId = BsonObjectID.generate);
}
cmd["documents"] = Bson([doc]);
MongoConnection conn = m_client.lockConnection();
enforceWireVersionConstraints(options, conn.description.maxWireVersion);
foreach (string k, v; serializeToBson(options).byKeyValue)
cmd[k] = v;
database.runCommandChecked(cmd).handleWriteResult(res);
return res;
}
/// ditto
InsertManyResult insertMany(T)(T[] documents, InsertManyOptions options = InsertManyOptions.init)
{
assert(m_client !is null, "Querying uninitialized MongoCollection.");
Bson cmd = Bson.emptyObject; // empty object because order is important
cmd["insert"] = Bson(m_name);
Bson[] arr = new Bson[documents.length];
BsonObjectID[size_t] insertedIds;
foreach (i, document; documents)
{
auto doc = serializeToBson(document);
arr[i] = doc;
enforce(doc.type == Bson.Type.object, "Can only insert objects into collections");
if ("_id" !in doc.get!(Bson[string]))
{
doc["_id"] = Bson(insertedIds[i] = BsonObjectID.generate);
}
}
cmd["documents"] = Bson(arr);
MongoConnection conn = m_client.lockConnection();
enforceWireVersionConstraints(options, conn.description.maxWireVersion);
foreach (string k, v; serializeToBson(options).byKeyValue)
cmd[k] = v;
auto res = InsertManyResult(insertedIds);
database.runCommandChecked(cmd).handleWriteResult!"insertedCount"(res);
return res;
}
/**
Deletes at most one document matching the query `filter`. The returned
result identifies how many documents have been deleted.
See_Also: $(LINK https://www.mongodb.com/docs/manual/reference/method/db.collection.deleteOne/#mongodb-method-db.collection.deleteOne)
Standards: $(LINK https://www.mongodb.com/docs/manual/reference/command/delete/)
*/
DeleteResult deleteOne(T)(T filter, DeleteOptions options = DeleteOptions.init)
@trusted {
int limit = 1;
return deleteImpl([filter], options, (&limit)[0 .. 1]);
}
/**
Deletes all documents matching the query `filter`. The returned result
identifies how many documents have been deleted.
See_Also: $(LINK https://www.mongodb.com/docs/manual/reference/method/db.collection.deleteMany/#mongodb-method-db.collection.deleteMany)
Standards: $(LINK https://www.mongodb.com/docs/manual/reference/command/delete/)
*/
DeleteResult deleteMany(T)(T filter, DeleteOptions options = DeleteOptions.init)
@safe
if (!is(T == DeleteOptions))
{
return deleteImpl([filter], options);
}
/**
Deletes all documents in the collection. The returned result identifies
how many documents have been deleted.
Same as calling `deleteMany` with `Bson.emptyObject` as filter.
Standards: $(LINK https://www.mongodb.com/docs/manual/reference/command/delete/)
*/
DeleteResult deleteAll(DeleteOptions options = DeleteOptions.init)
@safe {
return deleteImpl([Bson.emptyObject], options);
}
/// Implementation helper. It's possible to set custom delete limits with
/// this method, otherwise it's identical to `deleteOne` and `deleteMany`.
DeleteResult deleteImpl(T)(T[] queries, DeleteOptions options = DeleteOptions.init, scope int[] limits = null)
@safe {
assert(m_client !is null, "Querying uninitialized MongoCollection.");
alias FieldsMovedIntoChildren = AliasSeq!("limit", "collation", "hint");
Bson cmd = Bson.emptyObject; // empty object because order is important
cmd["delete"] = Bson(m_name);
MongoConnection conn = m_client.lockConnection();
enforceWireVersionConstraints(options, conn.description.maxWireVersion);
auto optionsBson = serializeToBson(options);
foreach (string k, v; optionsBson.byKeyValue)
if (!k.among!FieldsMovedIntoChildren)
cmd[k] = v;
Bson[] deletesBson = new Bson[queries.length];
foreach (i, q; queries)
{
auto deleteBson = Bson.emptyObject;
deleteBson["q"] = serializeToBson(q);
foreach (string k, v; optionsBson.byKeyValue)
if (k.among!FieldsMovedIntoChildren)
deleteBson[k] = v;
if (i < limits.length)
deleteBson["limit"] = Bson(limits[i]);
else
deleteBson["limit"] = Bson(0);
deletesBson[i] = deleteBson;
}
cmd["deletes"] = Bson(deletesBson);
DeleteResult res;
database.runCommandChecked(cmd).handleWriteResult!"deletedCount"(res);
return res;
}
/**
Replaces at most single document within the collection based on the
filter.
It's recommended to use the ReplaceOptions overload, but UpdateOptions
can be used as well. Note that the extra options inside UpdateOptions
may have no effect, possible warnings for this may only be handled by
MongoDB.
See_Also: $(LINK https://www.mongodb.com/docs/manual/reference/method/db.collection.replaceOne/#mongodb-method-db.collection.replaceOne)
Standards: $(LINK https://www.mongodb.com/docs/manual/reference/command/update/)
*/
UpdateResult replaceOne(T, U)(T filter, U replacement, ReplaceOptions options)
@safe {
UpdateOptions uoptions;
static foreach (f; FieldNameTuple!ReplaceOptions)
__traits(getMember, uoptions, f) = __traits(getMember, options, f);
Bson opts = Bson.emptyObject;
opts["multi"] = Bson(false);
return updateImpl([filter], [replacement], [opts], uoptions, true, false);
}
/// ditto
UpdateResult replaceOne(T, U)(T filter, U replacement, UpdateOptions options = UpdateOptions.init)
@safe {
Bson opts = Bson.emptyObject;
opts["multi"] = Bson(false);
return updateImpl([filter], [replacement], [opts], options, true, false);
}
///
@safe unittest {
import vibe.db.mongo.mongo;
void test(BsonObjectID id)
{
auto coll = connectMongoDB("127.0.0.1").getCollection("test");
// replaces the existing document with _id == id to `{_id: id, name: "Bob"}`
// or if it didn't exist before this will just insert, since we enabled `upsert`
ReplaceOptions options;
options.upsert = true;
coll.replaceOne(
["_id": id],
[
"_id": Bson(id),
"name": Bson("Bob")
],
options
);
}
}
/**
Updates at most single document within the collection based on the filter.
See_Also: $(LINK https://www.mongodb.com/docs/manual/reference/method/db.collection.updateOne/#mongodb-method-db.collection.updateOne)
Standards: $(LINK https://www.mongodb.com/docs/manual/reference/command/update/)
*/
UpdateResult updateOne(T, U)(T filter, U replacement, UpdateOptions options = UpdateOptions.init)
@safe {
Bson opts = Bson.emptyObject;
opts["multi"] = Bson(false);
return updateImpl([filter], [replacement], [opts], options, false, true);
}
/**
Updates all matching document within the collection based on the filter.
See_Also: $(LINK https://www.mongodb.com/docs/manual/reference/method/db.collection.updateMany/#mongodb-method-db.collection.updateMany)
Standards: $(LINK https://www.mongodb.com/docs/manual/reference/command/update/)
*/
UpdateResult updateMany(T, U)(T filter, U replacement, UpdateOptions options = UpdateOptions.init)
@safe {
Bson opts = Bson.emptyObject;
opts["multi"] = Bson(true);
return updateImpl([filter], [replacement], [opts], options, false, true);
}
/// Implementation helper. It's possible to set custom per-update object
/// options with this method, otherwise it's identical to `replaceOne`,
/// `updateOne` and `updateMany`.
UpdateResult updateImpl(T, U, O)(T[] queries, U[] documents, O[] perUpdateOptions, UpdateOptions options = UpdateOptions.init,
bool mustBeDocument = false, bool mustBeModification = false)
@safe
in(queries.length == documents.length && documents.length == perUpdateOptions.length,
"queries, documents and perUpdateOptions must have same length")
{
assert(m_client !is null, "Querying uninitialized MongoCollection.");
alias FieldsMovedIntoChildren = AliasSeq!("arrayFilters",
"collation",
"hint",
"upsert");
Bson cmd = Bson.emptyObject; // empty object because order is important
cmd["update"] = Bson(m_name);
MongoConnection conn = m_client.lockConnection();
enforceWireVersionConstraints(options, conn.description.maxWireVersion);
auto optionsBson = serializeToBson(options);
foreach (string k, v; optionsBson.byKeyValue)
if (!k.among!FieldsMovedIntoChildren)
cmd[k] = v;
Bson[] updatesBson = new Bson[queries.length];
foreach (i, q; queries)
{
auto updateBson = Bson.emptyObject;
auto qbson = serializeToBson(q);
updateBson["q"] = qbson;
auto ubson = serializeToBson(documents[i]);
if (mustBeDocument)
{
if (ubson.type != Bson.Type.object)
assert(false, "Passed in non-document into a place where only replacements are expected. "
~ "Maybe you want to call updateOne or updateMany instead?");
foreach (string k, v; ubson.byKeyValue)
{
if (k.startsWith("$"))
assert(false, "Passed in atomic modifiers (" ~ k
~ ") into a place where only replacements are expected. "
~ "Maybe you want to call updateOne or updateMany instead?");
debug {} // server checks that the rest is consistent (only $ or only non-$ allowed)
else break; // however in debug mode we check the full document, as we can give better error messages to the dev
}
}
if (mustBeModification)
{
if (ubson.type == Bson.Type.object)
{
bool anyDollar = false;
foreach (string k, v; ubson.byKeyValue)
{
if (k.startsWith("$"))
anyDollar = true;
debug {} // server checks that the rest is consistent (only $ or only non-$ allowed)
else break; // however in debug mode we check the full document, as we can give better error messages to the dev
// also nice side effect: if this is an empty document, this also matches the assert(false) branch.
}
if (!anyDollar)
assert(false, "Passed in a regular document into a place where only updates are expected. "
~ "Maybe you want to call replaceOne instead? "
~ "(this update call would otherwise replace the entire matched object with the passed in update object)");
}
}
updateBson["u"] = ubson;
foreach (string k, v; optionsBson.byKeyValue)
if (k.among!FieldsMovedIntoChildren)
updateBson[k] = v;
foreach (string k, v; perUpdateOptions[i].byKeyValue)
updateBson[k] = v;
updatesBson[i] = updateBson;
}
cmd["updates"] = Bson(updatesBson);
auto res = database.runCommandChecked(cmd);
auto ret = UpdateResult(
res["n"].to!long,
res["nModified"].to!long,
);
res.handleWriteResult(ret);
auto upserted = res["upserted"].opt!(Bson[]);
if (upserted.length)
{
ret.upsertedIds.length = upserted.length;
foreach (i, upsert; upserted)
{
ret.upsertedIds[i] = upsert["_id"].get!BsonObjectID;
}
}
return ret;
}
deprecated("Use the overload taking `FindOptions` instead, this method breaks in MongoDB 5.1 and onwards. Note: using a `$query` / `query` member to override the query arguments is no longer supported in the new overload.")
MongoCursor!R find(R = Bson, T, U)(T query, U returnFieldSelector, QueryFlags flags, int num_skip = 0, int num_docs_per_chunk = 0)
{
assert(m_client !is null, "Querying uninitialized MongoCollection.");
return MongoCursor!R(m_client, m_fullPath, flags, num_skip, num_docs_per_chunk, query, returnFieldSelector);
}
///
@safe deprecated unittest {
import vibe.db.mongo.mongo;
void test()
{
auto coll = connectMongoDB("127.0.0.1").getCollection("test");
// find documents with status == "A"
auto x = coll.find(["status": "A"], ["status": true], QueryFlags.none);
foreach (item; x)
{
// only for legacy overload
}
}
}
/**
Queries the collection for existing documents, limiting what fields are
returned by the database. (called projection)
See_Also:
- Querying: $(LINK http://www.mongodb.org/display/DOCS/Querying)
- Projection: $(LINK https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results/#std-label-projections)
- $(LREF findOne)
*/
MongoCursor!R find(R = Bson, T, U)(T query, U projection, FindOptions options = FindOptions.init)
if (!is(U == FindOptions))
{
options.projection = serializeToBson(projection);
return find(query, options);
}
///
@safe unittest {
import vibe.db.mongo.mongo;
void test()
{
auto coll = connectMongoDB("127.0.0.1").getCollection("test");
// find documents with status == "A", return list of {"item":..., "status":...}
coll.find(["status": "A"], ["item": 1, "status": 1]);
}
}
/**
Queries the collection for existing documents.
If no arguments are passed to find(), all documents of the collection will be returned.
See_Also:
- $(LINK http://www.mongodb.org/display/DOCS/Querying)
- $(LREF findOne)
*/
MongoCursor!R find(R = Bson, Q)(Q query, FindOptions options = FindOptions.init)
{
return MongoCursor!R(m_client, m_db.name, m_name, query, options);
}
///
@safe unittest {
import vibe.db.mongo.mongo;
void test()
{
auto coll = connectMongoDB("127.0.0.1").getCollection("test");
// find documents with status == "A"
coll.find(["status": "A"]);
}
}
/**
Queries all documents of the collection.
See_Also:
- $(LINK http://www.mongodb.org/display/DOCS/Querying)
- $(LREF findOne)
*/
MongoCursor!R find(R = Bson)() { return find!R(Bson.emptyObject, FindOptions.init); }
/// ditto
MongoCursor!R find(R = Bson)(FindOptions options) { return find!R(Bson.emptyObject, options); }
///
@safe unittest {
import vibe.db.mongo.mongo;
void test()
{
auto coll = connectMongoDB("127.0.0.1").getCollection("test");
// find all documents in the "test" collection.
coll.find();
}
}
deprecated("Use the overload taking `FindOptions` instead, this method breaks in MongoDB 5.1 and onwards. Note: using a `$query` / `query` member to override the query arguments is no longer supported in the new overload.")
auto findOne(R = Bson, T, U)(T query, U returnFieldSelector, QueryFlags flags)
{
import std.traits;
import std.typecons;
auto c = find!R(query, returnFieldSelector, flags, 0, 1);
static if (is(R == Bson)) {
foreach (doc; c) return doc;
return Bson(null);
} else static if (is(R == class) || isPointer!R || isDynamicArray!R || isAssociativeArray!R) {
foreach (doc; c) return doc;
return null;
} else {
foreach (doc; c) {
Nullable!R ret;
ret = doc;
return ret;
}
return Nullable!R.init;
}
}
/** Queries the collection for existing documents.
Returns:
By default, a Bson value of the matching document is returned, or $(D Bson(null))
when no document matched. For types R that are not Bson, the returned value is either
of type $(D R), or of type $(Nullable!R), if $(D R) is not a reference/pointer type.
The projection parameter limits what fields are returned by the database,
see projection documentation linked below.
Throws: Exception if a DB communication error or a query error occurred.
See_Also:
- Querying: $(LINK http://www.mongodb.org/display/DOCS/Querying)
- Projection: $(LINK https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results/#std-label-projections)
- $(LREF find)
*/
auto findOne(R = Bson, T, U)(T query, U projection, FindOptions options = FindOptions.init)
if (!is(U == FindOptions))
{
options.projection = serializeToBson(projection);
return findOne!(R, T)(query, options);
}
///
@safe unittest {
import vibe.db.mongo.mongo;
void test()
{
auto coll = connectMongoDB("127.0.0.1").getCollection("test");
// find documents with status == "A"
auto x = coll.findOne(["status": "A"], ["status": true, "otherField": true]);
// x now only contains _id (implicit, unless you make it `false`), status and otherField
}
}
/** Queries the collection for existing documents.
Returns:
By default, a Bson value of the matching document is returned, or $(D Bson(null))
when no document matched. For types R that are not Bson, the returned value is either
of type $(D R), or of type $(Nullable!R), if $(D R) is not a reference/pointer type.
Throws: Exception if a DB communication error or a query error occurred.
See_Also:
- $(LINK http://www.mongodb.org/display/DOCS/Querying)
- $(LREF find)
*/
auto findOne(R = Bson, T)(T query, FindOptions options = FindOptions.init)
{
import std.traits;
import std.typecons;
options.limit = 1;
auto c = find!R(query, options);
static if (is(R == Bson)) {
foreach (doc; c) return doc;
return Bson(null);
} else static if (is(R == class) || isPointer!R || isDynamicArray!R || isAssociativeArray!R) {
foreach (doc; c) return doc;
return null;
} else {
foreach (doc; c) {
Nullable!R ret;
ret = doc;
return ret;
}
return Nullable!R.init;
}
}
/**
Removes documents from the collection.
Throws: Exception if a DB communication error occurred.
See_Also: $(LINK http://www.mongodb.org/display/DOCS/Removing)
*/
deprecated("Use `deleteOne` or `deleteMany` taking DeleteOptions instead, this method breaks in MongoDB 5.1 and onwards.")
void remove(T)(T selector, DeleteFlags flags = DeleteFlags.None)
{
assert(m_client !is null, "Removing from uninitialized MongoCollection.");
auto conn = m_client.lockConnection();
ubyte[256] selector_buf = void;
conn.delete_(m_fullPath, flags, serializeToBson(selector, selector_buf));
}
/// ditto
deprecated("Use `deleteMany` taking `DeleteOptions` instead, this method breaks in MongoDB 5.1 and onwards.")
void remove()() { remove(Bson.emptyObject); }
/**
Combines a modify and find operation to a single atomic operation.
Params:
query = MongoDB query expression to identify the matched document
update = Update expression for the matched document
returnFieldSelector = Optional map of fields to return in the response
Throws:
An `Exception` will be thrown if an error occurs in the
communication with the database server.
See_Also: $(LINK http://docs.mongodb.org/manual/reference/command/findAndModify)
*/
Bson findAndModify(T, U, V)(T query, U update, V returnFieldSelector)
{
static struct CMD {
string findAndModify;
T query;
U update;
V fields;
}
CMD cmd;
cmd.findAndModify = m_name;
cmd.query = query;
cmd.update = update;
cmd.fields = returnFieldSelector;
auto ret = database.runCommandChecked(cmd);
return ret["value"];
}
/// ditto
Bson findAndModify(T, U)(T query, U update)
{
return findAndModify(query, update, null);
}
/**
Combines a modify and find operation to a single atomic operation with generic options support.
Params:
query = MongoDB query expression to identify the matched document
update = Update expression for the matched document
options = Generic BSON object that contains additional options
fields, such as `"new": true`
Throws:
An `Exception` will be thrown if an error occurs in the
communication with the database server.
See_Also: $(LINK http://docs.mongodb.org/manual/reference/command/findAndModify)
*/
Bson findAndModifyExt(T, U, V)(T query, U update, V options)
{
auto bopt = serializeToBson(options);
assert(bopt.type == Bson.Type.object,
"The options parameter to findAndModifyExt must be a BSON object.");
Bson cmd = Bson.emptyObject;
cmd["findAndModify"] = m_name;
cmd["query"] = serializeToBson(query);
cmd["update"] = serializeToBson(update);
bopt.opApply(delegate int(string key, Bson value) @safe {
cmd[key] = value;
return 0;
});
auto ret = database.runCommandChecked(cmd);
return ret["value"];
}
///
@safe unittest {
import vibe.db.mongo.mongo;
void test()
{
auto coll = connectMongoDB("127.0.0.1").getCollection("test");
coll.findAndModifyExt(["name": "foo"], ["$set": ["value": "bar"]], ["new": true]);
}
}
deprecated("deprecated since MongoDB v4.0, use countDocuments or estimatedDocumentCount instead")
ulong count(T)(T query)
{
return countImpl!T(query);
}
private ulong countImpl(T)(T query)
{
Bson cmd = Bson.emptyObject;
cmd["count"] = m_name;
cmd["query"] = serializeToBson(query);
auto reply = database.runCommandChecked(cmd);
switch (reply["n"].type) with (Bson.Type) {
default: assert(false, "Unsupported data type in BSON reply for COUNT");
case double_: return cast(ulong)reply["n"].get!double; // v2.x
case int_: return reply["n"].get!int; // v3.x
case long_: return reply["n"].get!long; // just in case
}
}
/**
Returns the count of documents that match the query for a collection or
view.
The method wraps the `$group` aggregation stage with a `$sum` expression
to perform the count.
Throws Exception if a DB communication error occurred.
See_Also: $(LINK https://www.mongodb.com/docs/manual/reference/method/db.collection.countDocuments/)
*/
ulong countDocuments(T)(T filter, CountOptions options = CountOptions.init)
{
// https://github.com/mongodb/specifications/blob/525dae0aa8791e782ad9dd93e507b60c55a737bb/source/crud/crud.rst#count-api-details
Bson[] pipeline = [Bson(["$match": serializeToBson(filter)])];
if (!options.skip.isNull)
pipeline ~= Bson(["$skip": Bson(options.skip.get)]);
if (!options.limit.isNull)
pipeline ~= Bson(["$limit": Bson(options.limit.get)]);
pipeline ~= Bson(["$group": Bson([
"_id": Bson(1),
"n": Bson(["$sum": Bson(1)])
])]);
AggregateOptions aggOptions;
foreach (i, field; options.tupleof)
{
enum name = CountOptions.tupleof[i].stringof;
static if (name != "filter" && name != "skip" && name != "limit")
__traits(getMember, aggOptions, name) = field;
}
auto reply = aggregate(pipeline, aggOptions);
return reply.empty ? 0 : reply.front["n"].to!long;
}
/**
Returns the count of all documents in a collection or view.
Throws Exception if a DB communication error occurred.
See_Also: $(LINK https://www.mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount/)
*/
ulong estimatedDocumentCount(EstimatedDocumentCountOptions options = EstimatedDocumentCountOptions.init)
{
// https://github.com/mongodb/specifications/blob/525dae0aa8791e782ad9dd93e507b60c55a737bb/source/crud/crud.rst#count-api-details
MongoConnection conn = m_client.lockConnection();
if (conn.description.satisfiesVersion(WireVersion.v49)) {
Bson[] pipeline = [
Bson(["$collStats": Bson(["count": Bson.emptyObject])]),
Bson(["$group": Bson([
"_id": Bson(1),
"n": Bson(["$sum": Bson("$count")])
])])
];
AggregateOptions aggOptions;
aggOptions.maxTimeMS = options.maxTimeMS;
auto reply = aggregate(pipeline, aggOptions).front;
return reply["n"].to!long;
} else {
return countImpl(null);
}
}
/**
Calculates aggregate values for the data in a collection.
Params:
pipeline = A sequence of data aggregation processes. These can
either be given as separate parameters, or as a single array
parameter.
Returns:
Returns the list of documents aggregated by the pipeline. The return
value is either a single `Bson` array value or a `MongoCursor`
(input range) of the requested document type.
Throws: Exception if a DB communication error occurred.
See_Also: $(LINK http://docs.mongodb.org/manual/reference/method/db.collection.aggregate)
*/
Bson aggregate(ARGS...)(ARGS pipeline) @safe
{
import std.traits : isArray;
static if (ARGS.length == 1 && isArray!(ARGS[0]))
auto convPipeline = pipeline;
else {
static struct Pipeline { @asArray ARGS pipeline; }
Bson[] convPipeline = serializeToBson(Pipeline(pipeline))["pipeline"].get!(Bson[]);
}
return aggregate(convPipeline, AggregateOptions.init).array.serializeToBson;
}
/// ditto
MongoCursor!R aggregate(R = Bson, S = Bson)(S[] pipeline, AggregateOptions options) @safe
{
assert(m_client !is null, "Querying uninitialized MongoCollection.");
Bson cmd = Bson.emptyObject; // empty object because order is important
cmd["aggregate"] = Bson(m_name);
cmd["$db"] = Bson(m_db.name);
cmd["pipeline"] = serializeToBson(pipeline);
MongoConnection conn = m_client.lockConnection();
enforceWireVersionConstraints(options, conn.description.maxWireVersion);
foreach (string k, v; serializeToBson(options).byKeyValue)
{
// spec recommends to omit cursor field when explain is true
if (!options.explain.isNull && options.explain.get && k == "cursor")
continue;
cmd[k] = v;
}
return MongoCursor!R(m_client, cmd,
!options.batchSize.isNull ? options.batchSize.get : 0,
!options.maxAwaitTimeMS.isNull ? options.maxAwaitTimeMS.get.msecs
: !options.maxTimeMS.isNull ? options.maxTimeMS.get.msecs
: Duration.max);
}
/// Example taken from the MongoDB documentation
@safe unittest {
import vibe.db.mongo.mongo;
void test() {
auto db = connectMongoDB("127.0.0.1").getDatabase("test");
auto results = db["coll"].aggregate(
["$match": ["status": "A"]],
["$group": ["_id": Bson("$cust_id"),
"total": Bson(["$sum": Bson("$amount")])]],
["$sort": ["total": -1]]);
}
}
/// The same example, but using an array of arguments with custom options
@safe unittest {
import vibe.db.mongo.mongo;
void test() {
auto db = connectMongoDB("127.0.0.1").getDatabase("test");
Bson[] args;
args ~= serializeToBson(["$match": ["status": "A"]]);
args ~= serializeToBson(["$group": ["_id": Bson("$cust_id"),
"total": Bson(["$sum": Bson("$amount")])]]);
args ~= serializeToBson(["$sort": ["total": -1]]);
AggregateOptions options;
options.cursor.batchSize = 10; // pre-fetch the first 10 results
auto results = db["coll"].aggregate(args, options);
}
}
/**
Returns an input range of all unique values for a certain field for
records matching the given query.
Params:
fieldName = Name of the field for which to collect unique values
query = The query used to select records
options = Options to apply
Returns:
An input range with items of type `R` (`Bson` by default) is
returned.
*/
auto distinct(R = Bson, Q)(string fieldName, Q query, DistinctOptions options = DistinctOptions.init)
{
assert(m_client !is null, "Querying uninitialized MongoCollection.");
Bson cmd = Bson.emptyObject; // empty object because order is important
cmd["distinct"] = Bson(m_name);
cmd["key"] = Bson(fieldName);
cmd["query"] = serializeToBson(query);
MongoConnection conn = m_client.lockConnection();
enforceWireVersionConstraints(options, conn.description.maxWireVersion);
foreach (string k, v; serializeToBson(options).byKeyValue)
cmd[k] = v;
import std.algorithm : map;
auto res = m_db.runCommandChecked(cmd);
static if (is(R == Bson)) return res["values"].byValue;
else return res["values"].byValue.map!(b => deserializeBson!R(b));
}
///
@safe unittest {
import std.algorithm : equal;
import vibe.db.mongo.mongo;
void test()
{
auto db = connectMongoDB("127.0.0.1").getDatabase("test");
auto coll = db["collection"];
coll.drop();
coll.insertOne(["a": "first", "b": "foo"]);
coll.insertOne(["a": "first", "b": "bar"]);
coll.insertOne(["a": "first", "b": "bar"]);
coll.insertOne(["a": "second", "b": "baz"]);
coll.insertOne(["a": "second", "b": "bam"]);
auto result = coll.distinct!string("b", ["a": "first"]);
assert(result.equal(["foo", "bar"]));
}
}
/*
following MongoDB standard API for the Index Management specification:
Standards: https://github.com/mongodb/specifications/blob/0c6e56141c867907aacf386e0cbe56d6562a0614/source/index-management.rst#standard-api
*/
deprecated("This is a legacy API, call createIndexes instead")
void ensureIndex(scope const(Tuple!(string, int))[] field_orders, IndexFlags flags = IndexFlags.none, Duration expire_time = 0.seconds)
@safe {
IndexModel[1] models;
IndexOptions options;
if (flags & IndexFlags.unique) options.unique = true;
if (flags & IndexFlags.dropDuplicates) options.dropDups = true;
if (flags & IndexFlags.background) options.background = true;
if (flags & IndexFlags.sparse) options.sparse = true;
if (flags & IndexFlags.expireAfterSeconds) options.expireAfter = expire_time;
models[0].options = options;
foreach (field; field_orders) {
models[0].add(field[0], field[1]);
}
createIndexes(models);
}
deprecated("This is a legacy API, call createIndexes instead. This API is not recommended to be used because of unstable dictionary ordering.")
void ensureIndex(int[string] field_orders, IndexFlags flags = IndexFlags.none, ulong expireAfterSeconds = 0)
@safe {
Tuple!(string, int)[] orders;
foreach (k, v; field_orders)
orders ~= tuple(k, v);
ensureIndex(orders, flags, expireAfterSeconds.seconds);
}
/**
Drops a single index from the collection by the index name.
Throws: `Exception` if it is attempted to pass in `*`.
Use dropIndexes() to remove all indexes instead.
*/
void dropIndex(string name, DropIndexOptions options = DropIndexOptions.init)
@safe {