-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
MongoCollection.cs
2651 lines (2423 loc) · 125 KB
/
MongoCollection.cs
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
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Threading;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Core.Misc;
using MongoDB.Driver.Core.Operations;
using MongoDB.Driver.Core.WireProtocol.Messages.Encoders;
using MongoDB.Driver.Wrappers;
using MongoDB.Shared;
namespace MongoDB.Driver
{
/// <summary>
/// Represents a MongoDB collection and the settings used to access it. This class is thread-safe.
/// </summary>
public abstract class MongoCollection
{
// private fields
private readonly MongoServer _server;
private readonly MongoDatabase _database;
private readonly MongoCollectionSettings _settings;
private readonly CollectionNamespace _collectionNamespace;
private readonly IOperationExecutor _operationExecutor;
// constructors
/// <summary>
/// Protected constructor for abstract base class.
/// </summary>
/// <param name="database">The database that contains this collection.</param>
/// <param name="name">The name of the collection.</param>
/// <param name="settings">The settings to use to access this collection.</param>
protected MongoCollection(MongoDatabase database, string name, MongoCollectionSettings settings)
: this(database, name, settings, new DefaultLegacyOperationExecutor())
{
}
internal MongoCollection(MongoDatabase database, string name, MongoCollectionSettings settings, IOperationExecutor operationExecutor)
{
if (database == null)
{
throw new ArgumentNullException("database");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
if (settings == null)
{
throw new ArgumentNullException("settings");
}
string message;
if (!database.IsCollectionNameValid(name, out message))
{
throw new ArgumentOutOfRangeException("name", message);
}
settings = settings.Clone();
settings.ApplyDefaultValues(database.Settings);
settings.Freeze();
_server = database.Server;
_database = database;
_collectionNamespace = new CollectionNamespace(_database.Name, name);
_settings = settings;
_operationExecutor = operationExecutor;
}
// public properties
/// <summary>
/// Gets the database that contains this collection.
/// </summary>
public virtual MongoDatabase Database
{
get { return _database; }
}
/// <summary>
/// Gets the fully qualified name of this collection.
/// </summary>
public virtual string FullName
{
get { return _collectionNamespace.FullName; }
}
/// <summary>
/// Gets the name of this collection.
/// </summary>
public virtual string Name
{
get { return _collectionNamespace.CollectionName; }
}
/// <summary>
/// Gets the settings being used to access this collection.
/// </summary>
public virtual MongoCollectionSettings Settings
{
get { return _settings; }
}
// internal properties
internal IOperationExecutor OperationExecutor => _operationExecutor;
// public methods
/// <summary>
/// Represents an aggregate framework query. The command is not sent to the server until the result is enumerated.
/// </summary>
/// <param name="args">The args.</param>
/// <returns>A sequence of documents.</returns>
public virtual IEnumerable<BsonDocument> Aggregate(AggregateArgs args)
{
return UsingImplicitSession(session => Aggregate(session, args));
}
private IEnumerable<BsonDocument> Aggregate(IClientSessionHandle session, AggregateArgs args)
{
if (args == null) { throw new ArgumentNullException("args"); }
if (args.Pipeline == null) { throw new ArgumentException("Pipeline is null.", "args"); }
var messageEncoderSettings = GetMessageEncoderSettings();
var lastStage = args.Pipeline.LastOrDefault();
var lastStageName = lastStage?.GetElement(0).Name;
if (lastStage != null && (lastStageName == "$out" || lastStageName == "$merge"))
{
var aggregateOperation = new AggregateToCollectionOperation(_collectionNamespace, args.Pipeline, messageEncoderSettings)
{
AllowDiskUse = args.AllowDiskUse,
BypassDocumentValidation = args.BypassDocumentValidation,
Collation = args.Collation,
MaxTime = args.MaxTime,
ReadConcern = _settings.ReadConcern,
ReadPreference = _settings.ReadPreference,
WriteConcern = _settings.WriteConcern
};
ExecuteWriteOperation(session, aggregateOperation);
CollectionNamespace outputCollectionNamespace;
var stageName = lastStage.GetElement(0).Name;
switch (stageName)
{
case "$out":
{
var outValue = lastStage[0];
DatabaseNamespace outputDatabaseNamespace;
string outputCollectionName;
if (outValue.IsString)
{
outputDatabaseNamespace = _collectionNamespace.DatabaseNamespace;
outputCollectionName = outValue.AsString;
}
else
{
outputDatabaseNamespace = new DatabaseNamespace(outValue["db"].AsString);
outputCollectionName = outValue["coll"].AsString;
}
outputCollectionNamespace = new CollectionNamespace(outputDatabaseNamespace, outputCollectionName);
}
break;
case "$merge":
{
var mergeArguments = lastStage[0].AsBsonDocument;
DatabaseNamespace outputDatabaseNamespace;
string outputCollectionName;
var into = mergeArguments["into"];
if (into.IsString)
{
outputDatabaseNamespace = _collectionNamespace.DatabaseNamespace;
outputCollectionName = into.AsString;
}
else
{
outputDatabaseNamespace = new DatabaseNamespace(into["db"].AsString);
outputCollectionName = into["coll"].AsString;
}
outputCollectionNamespace = new CollectionNamespace(outputDatabaseNamespace, outputCollectionName);
}
break;
default:
throw new ArgumentException($"Unexpected stage name: {stageName}.");
}
var resultSerializer = BsonDocumentSerializer.Instance;
var findOperation = new FindOperation<BsonDocument>(outputCollectionNamespace, resultSerializer, messageEncoderSettings)
{
BatchSize = args.BatchSize,
Collation = args.Collation,
MaxTime = args.MaxTime,
RetryRequested = _server.Settings.RetryReads
};
return new AggregateEnumerable(this, findOperation, ReadPreference.Primary);
}
else
{
var resultSerializer = BsonDocumentSerializer.Instance;
var operation = new AggregateOperation<BsonDocument>(_collectionNamespace, args.Pipeline, resultSerializer, messageEncoderSettings)
{
AllowDiskUse = args.AllowDiskUse,
BatchSize = args.BatchSize,
Collation = args.Collation,
MaxTime = args.MaxTime,
ReadConcern = _settings.ReadConcern,
RetryRequested = _server.Settings.RetryReads,
#pragma warning disable 618
UseCursor = args.OutputMode == AggregateOutputMode.Cursor
#pragma warning restore 618
};
return new AggregateEnumerable(this, operation, _settings.ReadPreference);
}
}
/// <summary>
/// Runs an aggregate command with explain set and returns the explain result.
/// </summary>
/// <param name="args">The args.</param>
/// <returns>The explain result.</returns>
public virtual CommandResult AggregateExplain(AggregateArgs args)
{
return UsingImplicitSession(session => AggregateExplain(session, args));
}
private CommandResult AggregateExplain(IClientSessionHandle session, AggregateArgs args)
{
var messageEncoderSettings = GetMessageEncoderSettings();
var operation = new AggregateExplainOperation(_collectionNamespace, args.Pipeline, messageEncoderSettings)
{
AllowDiskUse = args.AllowDiskUse,
Collation = args.Collation,
MaxTime = args.MaxTime
};
var response = ExecuteReadOperation(session, operation);
return new CommandResult(response);
}
/// <summary>
/// Counts the number of documents in this collection.
/// </summary>
/// <returns>The number of documents in this collection.</returns>
public virtual long Count()
{
var args = new CountArgs { Query = null };
return Count(args);
}
/// <summary>
/// Counts the number of documents in this collection that match a query.
/// </summary>
/// <param name="args">The args.</param>
/// <returns>
/// The number of documents in this collection that match the query.
/// </returns>
public virtual long Count(CountArgs args)
{
return UsingImplicitSession(session => Count(session, args));
}
private long Count(IClientSessionHandle session, CountArgs args)
{
if (args == null) { throw new ArgumentNullException("args"); }
var filter = args.Query == null ? null : new BsonDocumentWrapper(args.Query);
var operation = new CountOperation(_collectionNamespace, GetMessageEncoderSettings())
{
Collation = args.Collation,
Filter = filter,
Hint = args.Hint,
Limit = args.Limit,
MaxTime = args.MaxTime,
ReadConcern = _settings.ReadConcern,
RetryRequested = _server.Settings.RetryReads,
Skip = args.Skip
};
return ExecuteReadOperation(session, operation, args.ReadPreference);
}
/// <summary>
/// Counts the number of documents in this collection that match a query.
/// </summary>
/// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
/// <returns>The number of documents in this collection that match the query.</returns>
public virtual long Count(IMongoQuery query)
{
var args = new CountArgs { Query = query };
return Count(args);
}
/// <summary>
/// Creates an index for this collection.
/// </summary>
/// <param name="keys">The indexed fields (usually an IndexKeysDocument or constructed using the IndexKeys builder).</param>
/// <param name="options">The index options(usually an IndexOptionsDocument or created using the IndexOption builder).</param>
/// <returns>A WriteConcernResult.</returns>
public virtual WriteConcernResult CreateIndex(IMongoIndexKeys keys, IMongoIndexOptions options)
{
return UsingImplicitSession(session => CreateIndex(session, keys, options));
}
private WriteConcernResult CreateIndex(IClientSessionHandle session, IMongoIndexKeys keys, IMongoIndexOptions options)
{
try
{
var keysDocument = keys.ToBsonDocument();
var optionsDocument = options.ToBsonDocument();
var requests = new[] { new CreateIndexRequest(keysDocument) { AdditionalOptions = optionsDocument } };
var operation = new CreateIndexesOperation(_collectionNamespace, requests, GetMessageEncoderSettings())
{
WriteConcern = _settings.WriteConcern
};
ExecuteWriteOperation(session, operation);
return new WriteConcernResult(new BsonDocument("ok", 1));
}
catch (MongoCommandException ex)
{
var writeConcernResult = new WriteConcernResult(ex.Result);
throw new MongoWriteConcernException(ex.ConnectionId, ex.Message, writeConcernResult);
}
}
/// <summary>
/// Creates an index for this collection.
/// </summary>
/// <param name="keys">The indexed fields (usually an IndexKeysDocument or constructed using the IndexKeys builder).</param>
/// <returns>A WriteConcernResult.</returns>
public virtual WriteConcernResult CreateIndex(IMongoIndexKeys keys)
{
return CreateIndex(keys, IndexOptions.Null);
}
/// <summary>
/// Creates an index for this collection.
/// </summary>
/// <param name="keyNames">The names of the indexed fields.</param>
/// <returns>A WriteConcernResult.</returns>
public virtual WriteConcernResult CreateIndex(params string[] keyNames)
{
return CreateIndex(IndexKeys.Ascending(keyNames));
}
/// <summary>
/// Returns the distinct values for a given field.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="args">The args.</param>
/// <returns>The distint values of the field.</returns>
public IEnumerable<TValue> Distinct<TValue>(DistinctArgs args)
{
return UsingImplicitSession(session => Distinct<TValue>(session, args));
}
private IEnumerable<TValue> Distinct<TValue>(IClientSessionHandle session, DistinctArgs args)
{
if (args == null) { throw new ArgumentNullException("args"); }
if (args.Key == null) { throw new ArgumentException("Key is null.", "args"); }
var valueSerializer = (IBsonSerializer<TValue>)args.ValueSerializer ?? BsonSerializer.LookupSerializer<TValue>();
var operation = new DistinctOperation<TValue>(_collectionNamespace, valueSerializer, args.Key, GetMessageEncoderSettings())
{
Collation = args.Collation,
Filter = args.Query == null ? null : new BsonDocumentWrapper(args.Query),
MaxTime = args.MaxTime,
ReadConcern = _settings.ReadConcern,
RetryRequested = _server.Settings.RetryReads
};
return ExecuteReadOperation(session, operation).ToList();
}
/// <summary>
/// Returns the distinct values for a given field.
/// </summary>
/// <param name="key">The key of the field.</param>
/// <returns>The distint values of the field.</returns>
public virtual IEnumerable<BsonValue> Distinct(string key)
{
return Distinct<BsonValue>(new DistinctArgs
{
Key = key,
ValueSerializer = BsonValueSerializer.Instance
});
}
/// <summary>
/// Returns the distinct values for a given field for documents that match a query.
/// </summary>
/// <param name="key">The key of the field.</param>
/// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
/// <returns>The distint values of the field.</returns>
public virtual IEnumerable<BsonValue> Distinct(string key, IMongoQuery query)
{
return Distinct<BsonValue>(new DistinctArgs
{
Key = key,
Query = query,
ValueSerializer = BsonValueSerializer.Instance
});
}
/// <summary>
/// Returns the distinct values for a given field.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="key">The key of the field.</param>
/// <returns>The distint values of the field.</returns>
public virtual IEnumerable<TValue> Distinct<TValue>(string key)
{
return Distinct<TValue>(new DistinctArgs
{
Key = key
});
}
/// <summary>
/// Returns the distinct values for a given field for documents that match a query.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="key">The key of the field.</param>
/// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
/// <returns>The distint values of the field.</returns>
public virtual IEnumerable<TValue> Distinct<TValue>(string key, IMongoQuery query)
{
return Distinct<TValue>(new DistinctArgs
{
Key = key,
Query = query
});
}
/// <summary>
/// Drops this collection.
/// </summary>
/// <returns>A CommandResult.</returns>
public virtual CommandResult Drop()
{
return _database.DropCollection(_collectionNamespace.CollectionName);
}
/// <summary>
/// Drops all indexes on this collection.
/// </summary>
/// <returns>A <see cref="CommandResult"/>.</returns>
public virtual CommandResult DropAllIndexes()
{
return DropIndexByName("*");
}
/// <summary>
/// Drops an index on this collection.
/// </summary>
/// <param name="keys">The indexed fields (usually an IndexKeysDocument or constructed using the IndexKeys builder).</param>
/// <returns>A <see cref="CommandResult"/>.</returns>
public virtual CommandResult DropIndex(IMongoIndexKeys keys)
{
string indexName = IndexNameHelper.GetIndexName(keys.ToBsonDocument());
return DropIndexByName(indexName);
}
/// <summary>
/// Drops an index on this collection.
/// </summary>
/// <param name="keyNames">The names of the indexed fields.</param>
/// <returns>A <see cref="CommandResult"/>.</returns>
public virtual CommandResult DropIndex(params string[] keyNames)
{
string indexName = IndexNameHelper.GetIndexName(keyNames);
return DropIndexByName(indexName);
}
/// <summary>
/// Drops an index on this collection.
/// </summary>
/// <param name="indexName">The name of the index.</param>
/// <returns>A <see cref="CommandResult"/>.</returns>
public virtual CommandResult DropIndexByName(string indexName)
{
return UsingImplicitSession(session => DropIndexByName(session, indexName));
}
private CommandResult DropIndexByName(IClientSessionHandle session, string indexName)
{
var operation = new DropIndexOperation(_collectionNamespace, indexName, GetMessageEncoderSettings())
{
WriteConcern = _settings.WriteConcern
};
var response = ExecuteWriteOperation(session, operation);
return new CommandResult(response);
}
/// <summary>
/// Ensures that the desired index exists and creates it if it does not.
/// </summary>
/// <param name="keys">The indexed fields (usually an IndexKeysDocument or constructed using the IndexKeys builder).</param>
/// <param name="options">The index options(usually an IndexOptionsDocument or created using the IndexOption builder).</param>
[Obsolete("Use CreateIndex instead.")]
public virtual void EnsureIndex(IMongoIndexKeys keys, IMongoIndexOptions options)
{
CreateIndex(keys, options);
}
/// <summary>
/// Ensures that the desired index exists and creates it if it does not.
/// </summary>
/// <param name="keys">The indexed fields (usually an IndexKeysDocument or constructed using the IndexKeys builder).</param>
[Obsolete("Use CreateIndex instead.")]
public virtual void EnsureIndex(IMongoIndexKeys keys)
{
CreateIndex(keys);
}
/// <summary>
/// Ensures that the desired index exists and creates it if it does not.
/// </summary>
/// <param name="keyNames">The names of the indexed fields.</param>
[Obsolete("Use CreateIndex instead.")]
public virtual void EnsureIndex(params string[] keyNames)
{
CreateIndex(keyNames);
}
/// <summary>
/// Tests whether this collection exists.
/// </summary>
/// <returns>True if this collection exists.</returns>
public virtual bool Exists()
{
return _database.CollectionExists(_collectionNamespace.CollectionName);
}
/// <summary>
/// Returns a cursor that can be used to find all documents in this collection as TDocuments.
/// </summary>
/// <typeparam name="TDocument">The nominal type of the documents.</typeparam>
/// <returns>A <see cref="MongoCursor{TDocument}"/>.</returns>
public virtual MongoCursor<TDocument> FindAllAs<TDocument>()
{
return FindAs<TDocument>(Query.Null);
}
/// <summary>
/// Returns a cursor that can be used to find all documents in this collection as TDocuments.
/// </summary>
/// <param name="documentType">The nominal type of the documents.</param>
/// <returns>A <see cref="MongoCursor{TDocument}"/>.</returns>
public virtual MongoCursor FindAllAs(Type documentType)
{
return FindAs(documentType, Query.Null);
}
/// <summary>
/// Finds one matching document using the query and sortBy parameters and applies the specified update to it.
/// </summary>
/// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
/// <param name="sortBy">The sort order to select one of the matching documents.</param>
/// <param name="update">The update to apply to the matching document.</param>
/// <returns>A <see cref="FindAndModifyResult"/>.</returns>
[Obsolete("Use the overload of FindAndModify that has a FindAndModifyArgs parameter instead.")]
public virtual FindAndModifyResult FindAndModify(IMongoQuery query, IMongoSortBy sortBy, IMongoUpdate update)
{
var args = new FindAndModifyArgs { Query = query, SortBy = sortBy, Update = update };
return FindAndModify(args);
}
/// <summary>
/// Finds one matching document using the query and sortBy parameters and applies the specified update to it.
/// </summary>
/// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
/// <param name="sortBy">The sort order to select one of the matching documents.</param>
/// <param name="update">The update to apply to the matching document.</param>
/// <param name="returnNew">Whether to return the new or old version of the modified document in the <see cref="FindAndModifyResult"/>.</param>
/// <returns>A <see cref="FindAndModifyResult"/>.</returns>
[Obsolete("Use the overload of FindAndModify that has a FindAndModifyArgs parameter instead.")]
public virtual FindAndModifyResult FindAndModify(
IMongoQuery query,
IMongoSortBy sortBy,
IMongoUpdate update,
bool returnNew)
{
var versionReturned = returnNew ? FindAndModifyDocumentVersion.Modified : FindAndModifyDocumentVersion.Original;
var args = new FindAndModifyArgs { Query = query, SortBy = sortBy, Update = update, VersionReturned = versionReturned };
return FindAndModify(args);
}
/// <summary>
/// Finds one matching document using the query and sortBy parameters and applies the specified update to it.
/// </summary>
/// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
/// <param name="sortBy">The sort order to select one of the matching documents.</param>
/// <param name="update">The update to apply to the matching document.</param>
/// <param name="returnNew">Whether to return the new or old version of the modified document in the <see cref="FindAndModifyResult"/>.</param>
/// <param name="upsert">Whether to do an upsert if no matching document is found.</param>
/// <returns>A <see cref="FindAndModifyResult"/>.</returns>
[Obsolete("Use the overload of FindAndModify that has a FindAndModifyArgs parameter instead.")]
public virtual FindAndModifyResult FindAndModify(
IMongoQuery query,
IMongoSortBy sortBy,
IMongoUpdate update,
bool returnNew,
bool upsert)
{
var versionReturned = returnNew ? FindAndModifyDocumentVersion.Modified : FindAndModifyDocumentVersion.Original;
var args = new FindAndModifyArgs { Query = query, SortBy = sortBy, Update = update, VersionReturned = versionReturned, Upsert = upsert };
return FindAndModify(args);
}
/// <summary>
/// Finds one matching document using the query and sortBy parameters and applies the specified update to it.
/// </summary>
/// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
/// <param name="sortBy">The sort order to select one of the matching documents.</param>
/// <param name="update">The update to apply to the matching document.</param>
/// <param name="fields">Which fields of the modified document to return in the <see cref="FindAndModifyResult"/>.</param>
/// <param name="returnNew">Whether to return the new or old version of the modified document in the <see cref="FindAndModifyResult"/>.</param>
/// <param name="upsert">Whether to do an upsert if no matching document is found.</param>
/// <returns>A <see cref="FindAndModifyResult"/>.</returns>
[Obsolete("Use the overload of FindAndModify that has a FindAndModifyArgs parameter instead.")]
public virtual FindAndModifyResult FindAndModify(
IMongoQuery query,
IMongoSortBy sortBy,
IMongoUpdate update,
IMongoFields fields,
bool returnNew,
bool upsert)
{
var versionReturned = returnNew ? FindAndModifyDocumentVersion.Modified : FindAndModifyDocumentVersion.Original;
var args = new FindAndModifyArgs { Query = query, SortBy = sortBy, Update = update, Fields = fields, VersionReturned = versionReturned, Upsert = upsert };
return FindAndModify(args);
}
/// <summary>
/// Finds one matching document using the supplied arguments and applies the specified update to it.
/// </summary>
/// <param name="args">The args.</param>
/// <returns>A <see cref="FindAndModifyResult"/>.</returns>
public virtual FindAndModifyResult FindAndModify(FindAndModifyArgs args)
{
return UsingImplicitSession(session => FindAndModify(session, args));
}
private FindAndModifyResult FindAndModify(IClientSessionHandle session, FindAndModifyArgs args)
{
if (args == null) { throw new ArgumentNullException("args"); }
if (args.Update == null) { throw new ArgumentException("Update is null.", "args"); }
var filter = args.Query == null ? new BsonDocument() : new BsonDocumentWrapper(args.Query);
var updateDocument = args.Update.ToBsonDocument();
var resultSerializer = BsonDocumentSerializer.Instance;
var messageEncoderSettings = GetMessageEncoderSettings();
var projection = args.Fields == null ? null : new BsonDocumentWrapper(args.Fields);
var returnDocument = !args.VersionReturned.HasValue || args.VersionReturned.Value == FindAndModifyDocumentVersion.Original
? Core.Operations.ReturnDocument.Before
: Core.Operations.ReturnDocument.After;
var sort = args.SortBy == null ? null : new BsonDocumentWrapper(args.SortBy);
FindAndModifyOperationBase<BsonDocument> operation;
if (updateDocument.ElementCount > 0 && updateDocument.GetElement(0).Name.StartsWith("$", StringComparison.Ordinal))
{
operation = new FindOneAndUpdateOperation<BsonDocument>(_collectionNamespace, filter, updateDocument, resultSerializer, messageEncoderSettings)
{
BypassDocumentValidation = args.BypassDocumentValidation,
Collation = args.Collation,
IsUpsert = args.Upsert,
MaxTime = args.MaxTime,
Projection = projection,
ReturnDocument = returnDocument,
Sort = sort,
WriteConcern = _settings.WriteConcern
};
}
else
{
var replacement = updateDocument;
operation = new FindOneAndReplaceOperation<BsonDocument>(_collectionNamespace, filter, replacement, resultSerializer, messageEncoderSettings)
{
BypassDocumentValidation = args.BypassDocumentValidation,
Collation = args.Collation,
IsUpsert = args.Upsert,
MaxTime = args.MaxTime,
Projection = projection,
RetryRequested = _server.Settings.RetryWrites,
ReturnDocument = returnDocument,
Sort = sort,
WriteConcern = _settings.WriteConcern
};
}
try
{
var response = ExecuteWriteOperation(session, operation);
return new FindAndModifyResult(response);
}
catch (MongoCommandException ex)
{
if (ex.ErrorMessage == "No matching object found")
{
// create a new command result with what the server should have responded
var response = new BsonDocument
{
{ "value", BsonNull.Value },
{ "ok", true }
};
return new FindAndModifyResult(response);
}
throw;
}
}
/// <summary>
/// Finds one matching document using the query and sortBy parameters and removes it from this collection.
/// </summary>
/// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
/// <param name="sortBy">The sort order to select one of the matching documents.</param>
/// <returns>A <see cref="FindAndModifyResult"/>.</returns>
[Obsolete("Use the overload of FindAndRemove that has a FindAndRemoveArgs parameter instead.")]
public virtual FindAndModifyResult FindAndRemove(IMongoQuery query, IMongoSortBy sortBy)
{
var args = new FindAndRemoveArgs { Query = query, SortBy = sortBy };
return FindAndRemove(args);
}
/// <summary>
/// Finds one matching document using the supplied args and removes it from this collection.
/// </summary>
/// <param name="args">The args.</param>
/// <returns>A <see cref="FindAndModifyResult"/>.</returns>
public virtual FindAndModifyResult FindAndRemove(FindAndRemoveArgs args)
{
return UsingImplicitSession(session => FindAndRemove(session, args));
}
private FindAndModifyResult FindAndRemove(IClientSessionHandle session, FindAndRemoveArgs args)
{
if (args == null) { throw new ArgumentNullException("args"); }
var filter = args.Query == null ? new BsonDocument() : new BsonDocumentWrapper(args.Query);
var resultSerializer = BsonDocumentSerializer.Instance;
var messageEncoderSettings = GetMessageEncoderSettings();
var projection = args.Fields == null ? null : new BsonDocumentWrapper(args.Fields);
var sort = args.SortBy == null ? null : new BsonDocumentWrapper(args.SortBy);
var operation = new FindOneAndDeleteOperation<BsonDocument>(_collectionNamespace, filter, resultSerializer, messageEncoderSettings)
{
Collation = args.Collation,
MaxTime = args.MaxTime,
Projection = projection,
RetryRequested = _server.Settings.RetryWrites,
Sort = sort,
WriteConcern = _settings.WriteConcern
};
try
{
var response = ExecuteWriteOperation(session, operation);
return new FindAndModifyResult(response);
}
catch (MongoCommandException ex)
{
if (ex.ErrorMessage == "No matching object found")
{
// create a new command result with what the server should have responded
var response = new BsonDocument
{
{ "value", BsonNull.Value },
{ "ok", true }
};
return new FindAndModifyResult(response);
}
throw;
}
}
/// <summary>
/// Returns a cursor that can be used to find all documents in this collection that match the query as TDocuments.
/// </summary>
/// <typeparam name="TDocument">The type to deserialize the documents as.</typeparam>
/// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
/// <returns>A <see cref="MongoCursor{TDocument}"/>.</returns>
public virtual MongoCursor<TDocument> FindAs<TDocument>(IMongoQuery query)
{
var serializer = BsonSerializer.LookupSerializer(typeof(TDocument));
return FindAs<TDocument>(query, serializer);
}
/// <summary>
/// Returns a cursor that can be used to find all documents in this collection that match the query as TDocuments.
/// </summary>
/// <param name="documentType">The nominal type of the documents.</param>
/// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
/// <returns>A <see cref="MongoCursor{TDocument}"/>.</returns>
public virtual MongoCursor FindAs(Type documentType, IMongoQuery query)
{
var serializer = BsonSerializer.LookupSerializer(documentType);
return FindAs(documentType, query, serializer);
}
/// <summary>
/// Returns one document in this collection as a TDocument.
/// </summary>
/// <typeparam name="TDocument">The type to deserialize the documents as.</typeparam>
/// <returns>A TDocument (or null if not found).</returns>
public virtual TDocument FindOneAs<TDocument>()
{
var args = new FindOneArgs { Query = null };
return FindOneAs<TDocument>(args);
}
/// <summary>
/// Returns one document in this collection as a TDocument.
/// </summary>
/// <typeparam name="TDocument">The type of the document.</typeparam>
/// <param name="args">The args.</param>
/// <returns>A TDocument (or null if not found).</returns>
public virtual TDocument FindOneAs<TDocument>(FindOneArgs args)
{
return UsingImplicitSession(session => FindOneAs<TDocument>(session, args));
}
private TDocument FindOneAs<TDocument>(IClientSessionHandle session, FindOneArgs args)
{
var modifiers = new BsonDocument();
var queryDocument = args.Query == null ? new BsonDocument() : args.Query.ToBsonDocument();
var serializer = BsonSerializer.LookupSerializer<TDocument>();
var messageEncoderSettings = GetMessageEncoderSettings();
var fields = args.Fields == null ? null : args.Fields.ToBsonDocument();
if (args.Hint != null)
{
modifiers["$hint"] = IndexNameHelper.GetIndexName(args.Hint);
}
var operation = new FindOperation<TDocument>(_collectionNamespace, serializer, messageEncoderSettings)
{
Collation = args.Collation,
Filter = queryDocument,
Limit = -1,
MaxTime = args.MaxTime,
Projection = fields,
RetryRequested = _server.Settings.RetryReads,
Skip = args.Skip,
Sort = args.SortBy.ToBsonDocument()
};
using (var cursor = ExecuteReadOperation(session, operation, args.ReadPreference))
{
if (cursor.MoveNext(CancellationToken.None))
{
return cursor.Current.SingleOrDefault();
}
return default(TDocument);
}
}
/// <summary>
/// Returns one document in this collection that matches a query as a TDocument.
/// </summary>
/// <typeparam name="TDocument">The type to deserialize the documents as.</typeparam>
/// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
/// <returns>A TDocument (or null if not found).</returns>
public virtual TDocument FindOneAs<TDocument>(IMongoQuery query)
{
var args = new FindOneArgs { Query = query };
return FindOneAs<TDocument>(args);
}
/// <summary>
/// Returns one document in this collection as a TDocument.
/// </summary>
/// <param name="documentType">The nominal type of the documents.</param>
/// <returns>A document (or null if not found).</returns>
public virtual object FindOneAs(Type documentType)
{
var args = new FindOneArgs { Query = null };
return FindOneAs(documentType, args);
}
/// <summary>
/// Returns one document in this collection as a TDocument.
/// </summary>
/// <param name="documentType">The nominal type of the documents.</param>
/// <param name="args">The args.</param>
/// <returns>A document (or null if not found).</returns>
public virtual object FindOneAs(Type documentType, FindOneArgs args)
{
var methodDefinition = GetType().GetTypeInfo().GetMethod("FindOneAs", new Type[] { typeof(FindOneArgs) });
var methodInfo = methodDefinition.MakeGenericMethod(documentType);
try
{
return methodInfo.Invoke(this, new object[] { args });
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
/// <summary>
/// Returns one document in this collection that matches a query as a TDocument.
/// </summary>
/// <param name="documentType">The type to deserialize the documents as.</param>
/// <param name="query">The query (usually a QueryDocument or constructed using the Query builder).</param>
/// <returns>A TDocument (or null if not found).</returns>
public virtual object FindOneAs(Type documentType, IMongoQuery query)
{
var args = new FindOneArgs { Query = query };
return FindOneAs(documentType, args);
}
/// <summary>
/// Returns a cursor that can be used to find one document in this collection by its _id value as a TDocument.
/// </summary>
/// <typeparam name="TDocument">The nominal type of the document.</typeparam>
/// <param name="id">The id of the document.</param>
/// <returns>A TDocument (or null if not found).</returns>
public virtual TDocument FindOneByIdAs<TDocument>(BsonValue id)
{
return FindOneAs<TDocument>(Query.EQ("_id", id));
}
/// <summary>
/// Returns a cursor that can be used to find one document in this collection by its _id value as a TDocument.
/// </summary>
/// <param name="documentType">The nominal type of the document.</param>
/// <param name="id">The id of the document.</param>
/// <returns>A TDocument (or null if not found).</returns>
public virtual object FindOneByIdAs(Type documentType, BsonValue id)
{
return FindOneAs(documentType, Query.EQ("_id", id));
}
/// <summary>
/// Runs a geoHaystack search command on this collection.
/// </summary>
/// <typeparam name="TDocument">The type of the found documents.</typeparam>
/// <param name="x">The x coordinate of the starting location.</param>
/// <param name="y">The y coordinate of the starting location.</param>
/// <param name="options">The options for the geoHaystack search (null if none).</param>
/// <returns>A <see cref="GeoNearResult{TDocument}"/>.</returns>
[Obsolete("Use the overload of GeoHaystackSearchAs that has a GeoHaystackSearchArgs parameter instead.")]
public virtual GeoHaystackSearchResult<TDocument> GeoHaystackSearchAs<TDocument>(
double x,
double y,
IMongoGeoHaystackSearchOptions options)
{
var optionsDocument = options.ToBsonDocument();
var args = new GeoHaystackSearchArgs
{
Near = new XYPoint(x, y),
MaxDistance = optionsDocument.Contains("maxDistance") ? (int?)optionsDocument["maxDistance"].ToInt32() : null,
Limit = optionsDocument.Contains("limit") ? (int?)optionsDocument["limit"].ToInt32() : null
};
if (optionsDocument.Contains("search"))
{
var searchElement = optionsDocument["search"].AsBsonDocument.GetElement(0);
args.AdditionalFieldName = searchElement.Name;
args.AdditionalFieldValue = searchElement.Value;
}
return GeoHaystackSearchAs<TDocument>(args);
}
/// <summary>
/// Runs a geoHaystack search command on this collection.
/// </summary>
/// <typeparam name="TDocument">The type of the found documents.</typeparam>
/// <param name="args">The args.</param>
/// <returns>A <see cref="GeoNearResult{TDocument}"/>.</returns>
[Obsolete("GeoHaystack indexes were deprecated in server version 4.4.")]
public virtual GeoHaystackSearchResult<TDocument> GeoHaystackSearchAs<TDocument>(GeoHaystackSearchArgs args)
{
return UsingImplicitSession(session => GeoHaystackSearchAs<TDocument>(session, args));
}
#pragma warning disable 618
private GeoHaystackSearchResult<TDocument> GeoHaystackSearchAs<TDocument>(IClientSessionHandle session, GeoHaystackSearchArgs args)
{
if (args == null) { throw new ArgumentNullException("args"); }
if (args.Near == null) { throw new ArgumentException("Near is null.", "args"); }