forked from mongodb/mongo-java-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDBCollection.java
More file actions
2143 lines (1930 loc) · 87.5 KB
/
Copy pathDBCollection.java
File metadata and controls
2143 lines (1930 loc) · 87.5 KB
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 (c) 2008-2014 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.
*/
package com.mongodb;
// Mongo
import org.bson.types.ObjectId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* This class provides a skeleton implementation of a database collection. <p>A typical invocation sequence is thus
* <pre>
* {@code
* MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
* DB db = mongo.getDB("mydb");
* DBCollection collection = db.getCollection("test"); }
* </pre>
* To get a collection to use, just specify the name of the collection to the getCollection(String collectionName) method:
* <pre>
* {@code
* DBCollection coll = db.getCollection("testCollection"); }
* </pre>
* Once you have the collection object, you can insert documents into the collection:
* <pre>
* {@code
* BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database")
* .append("count", 1)
* .append("info", new BasicDBObject("x", 203).append("y", 102));
* coll.insert(doc); }
* </pre>
* To show that the document we inserted in the previous step is there, we can do a simple findOne() operation to get the first document in
* the collection:
* <pre>
* {@code
* DBObject myDoc = coll.findOne();
* System.out.println(myDoc); }
* </pre>
*/
@SuppressWarnings("unchecked")
public abstract class DBCollection {
/**
* Insert documents into a collection. If the collection does not exists on the server, then it will be created. If the new document
* does not contain an '_id' field, it will be added.
*
* @param arr {@code DBObject}'s to be inserted
* @param concern {@code WriteConcern} to be used during operation
* @return the result of the operation
* @throws MongoException if the operation fails
* @dochub insert Insert
*/
public WriteResult insert(DBObject[] arr , WriteConcern concern ){
return insert( arr, concern, getDBEncoder());
}
/**
* Insert documents into a collection. If the collection does not exists on the server, then it will be created. If the new document
* does not contain an '_id' field, it will be added.
*
* @param arr {@code DBObject}'s to be inserted
* @param concern {@code WriteConcern} to be used during operation
* @param encoder {@code DBEncoder} to be used
* @return the result of the operation
* @throws MongoException if the operation fails
* @dochub insert Insert
*/
public WriteResult insert(DBObject[] arr , WriteConcern concern, DBEncoder encoder) {
return insert(Arrays.asList(arr), concern, encoder);
}
/**
* Insert a document into a collection. If the collection does not exists on the server, then it will be created. If the new document
* does not contain an '_id' field, it will be added.
*
* @param o {@code DBObject} to be inserted
* @param concern {@code WriteConcern} to be used during operation
* @return the result of the operation
* @throws MongoException if the operation fails
* @dochub insert Insert
*/
public WriteResult insert(DBObject o , WriteConcern concern ){
return insert( Arrays.asList(o) , concern );
}
/**
* Insert documents into a collection. If the collection does not exists on the server, then it will be created. If the new document
* does not contain an '_id' field, it will be added. Collection wide {@code WriteConcern} will be used.
*
* @param arr {@code DBObject}'s to be inserted
* @return the result of the operation
* @throws MongoException if the operation fails
* @mongodb.driver.manual tutorial/insert-documents/ Insert
*/
public WriteResult insert(DBObject ... arr){
return insert( arr , getWriteConcern() );
}
/**
* Insert documents into a collection. If the collection does not exists on the server, then it will be created. If the new document
* does not contain an '_id' field, it will be added.
*
* @param arr {@code DBObject}'s to be inserted
* @param concern {@code WriteConcern} to be used during operation
* @return the result of the operation
* @throws MongoException if the operation fails
* @mongodb.driver.manual tutorial/insert-documents/ Insert
*/
public WriteResult insert(WriteConcern concern, DBObject ... arr){
return insert( arr, concern );
}
/**
* Insert documents into a collection. If the collection does not exists on the server, then it will be created. If the new document
* does not contain an '_id' field, it will be added.
*
* @param list list of {@code DBObject} to be inserted
* @return the result of the operation
* @throws MongoException if the operation fails
* @mongodb.driver.manual tutorial/insert-documents/ Insert
*/
public WriteResult insert(List<DBObject> list ){
return insert( list, getWriteConcern() );
}
/**
* Insert documents into a collection. If the collection does not exists on the server, then it will be created. If the new document
* does not contain an '_id' field, it will be added.
*
* @param list list of {@code DBObject}'s to be inserted
* @param concern {@code WriteConcern} to be used during operation
* @return the result of the operation
* @throws MongoException if the operation fails
* @mongodb.driver.manual tutorial/insert-documents/ Insert
*/
public WriteResult insert(List<DBObject> list, WriteConcern concern ){
return insert(list, concern, getDBEncoder() );
}
/**
* Insert documents into a collection. If the collection does not exists on the server, then it will be created. If the new document
* does not contain an '_id' field, it will be added.
*
* @param list a list of {@code DBObject}'s to be inserted
* @param concern {@code WriteConcern} to be used during operation
* @param encoder {@code DBEncoder} to use to serialise the documents
* @return the result of the operation
* @throws MongoException if the operation fails
* @mongodb.driver.manual tutorial/insert-documents/ Insert
*/
public abstract WriteResult insert(List<DBObject> list, WriteConcern concern, DBEncoder encoder);
/**
* Modify an existing document or documents in collection. By default the method updates a single document. The query parameter employs
* the same query selectors, as used in {@link DBCollection#find(DBObject)}.
*
* @param q the selection criteria for the update
* @param o the modifications to apply
* @param upsert when true, inserts a document if no document matches the update query criteria
* @param multi when true, updates all documents in the collection that match the update query criteria, otherwise only updates one
* @param concern {@code WriteConcern} to be used during operation
* @return the result of the operation
* @throws MongoException
* @mongodb.driver.manual tutorial/modify-documents/ Modify
*/
public WriteResult update( DBObject q , DBObject o , boolean upsert , boolean multi , WriteConcern concern ){
return update( q, o, upsert, multi, concern, getDBEncoder());
}
/**
* Modify an existing document or documents in collection. By default the method updates a single document. The query parameter employs
* the same query selectors, as used in {@link DBCollection#find(DBObject)}.
*
* @param q the selection criteria for the update
* @param o the modifications to apply
* @param upsert when true, inserts a document if no document matches the update query criteria
* @param multi when true, updates all documents in the collection that match the update query criteria, otherwise only updates one
* @param concern {@code WriteConcern} to be used during operation
* @param encoder the DBEncoder to use
* @return the result of the operation
* @throws MongoException
* @mongodb.driver.manual tutorial/modify-documents/ Modify
*/
public abstract WriteResult update( DBObject q , DBObject o , boolean upsert , boolean multi , WriteConcern concern, DBEncoder encoder );
/**
* Modify an existing document or documents in collection. By default the method updates a single document. The query parameter employs
* the same query selectors, as used in {@link DBCollection#find(DBObject)}. Calls {@link DBCollection#update(com.mongodb.DBObject,
* com.mongodb.DBObject, boolean, boolean, com.mongodb.WriteConcern)} with default WriteConcern.
*
* @param q the selection criteria for the update
* @param o the modifications to apply
* @param upsert when true, inserts a document if no document matches the update query criteria
* @param multi when true, updates all documents in the collection that match the update query criteria, otherwise only updates one
* @return the result of the operation
* @throws MongoException
* @mongodb.driver.manual tutorial/modify-documents/ Modify
*/
public WriteResult update( DBObject q , DBObject o , boolean upsert , boolean multi ){
return update( q , o , upsert , multi , getWriteConcern() );
}
/**
* Modify an existing document or documents in collection. By default the method updates a single document. The query parameter employs
* the same query selectors, as used in {@link DBCollection#find(DBObject)}. Calls {@link DBCollection#update(com.mongodb.DBObject,
* com.mongodb.DBObject, boolean, boolean)} with upsert=false and multi=false
*
* @param q the selection criteria for the update
* @param o the modifications to apply
* @return the result of the operation
* @throws MongoException
* @mongodb.driver.manual tutorial/modify-documents/ Modify
*/
public WriteResult update( DBObject q , DBObject o ){
return update( q , o , false , false );
}
/**
* Modify an existing document or documents in collection. By default the method updates a single document. The query parameter employs
* the same query selectors, as used in {@link DBCollection#find()}. Calls {@link DBCollection#update(com.mongodb.DBObject,
* com.mongodb.DBObject, boolean, boolean)} with upsert=false and multi=true
*
* @param q the selection criteria for the update
* @param o the modifications to apply
* @return the result of the operation
* @throws MongoException
* @mongodb.driver.manual tutorial/modify-documents/ Modify
*/
public WriteResult updateMulti( DBObject q , DBObject o ){
return update( q , o , false , true );
}
/**
* Adds any necessary fields to a given object before saving it to the collection.
* @param o object to which to add the fields
*/
protected abstract void doapply( DBObject o );
/**
* Remove documents from a collection.
*
* @param o the deletion criteria using query operators. Omit the query parameter or pass an empty document to delete all
* documents in the collection.
* @param concern {@code WriteConcern} to be used during operation
* @return the result of the operation
* @throws MongoException
* @mongodb.driver.manual tutorial/remove-documents/ Remove
*/
public WriteResult remove( DBObject o , WriteConcern concern ){
return remove( o, concern, getDBEncoder());
}
/**
* Remove documents from a collection.
*
* @param o the deletion criteria using query operators. Omit the query parameter or pass an empty document to delete all
* documents in the collection.
* @param concern {@code WriteConcern} to be used during operation
* @param encoder {@code DBEncoder} to be used
* @return the result of the operation
* @throws MongoException
* @mongodb.driver.manual tutorial/remove-documents/ Remove
*/
public abstract WriteResult remove( DBObject o , WriteConcern concern, DBEncoder encoder );
/**
* Remove documents from a collection. Calls {@link DBCollection#remove(com.mongodb.DBObject, com.mongodb.WriteConcern)} with the
* default WriteConcern
*
* @param o the deletion criteria using query operators. Omit the query parameter or pass an empty document to delete all documents in
* the collection.
* @return the result of the operation
* @throws MongoException
* @mongodb.driver.manual tutorial/remove-documents/ Remove
*/
public WriteResult remove( DBObject o ){
return remove( o , getWriteConcern() );
}
/**
* Finds objects
*/
abstract QueryResultIterator find(DBObject ref, DBObject fields, int numToSkip, int batchSize, int limit, int options,
ReadPreference readPref, DBDecoder decoder);
abstract QueryResultIterator find(DBObject ref, DBObject fields, int numToSkip, int batchSize, int limit, int options,
ReadPreference readPref, DBDecoder decoder, DBEncoder encoder);
/**
* Calls {@link DBCollection#find(com.mongodb.DBObject, com.mongodb.DBObject, int, int)} and applies the query options
*
* @param query query used to search
* @param fields the fields of matching objects to return
* @param numToSkip number of objects to skip
* @param batchSize the batch size. This option has a complex behavior, see {@link DBCursor#batchSize(int) }
* @param options see {@link com.mongodb.Bytes} QUERYOPTION_*
* @return the cursor
* @throws MongoException
* @mongodb.driver.manual tutorial/query-documents/ Query
* @deprecated use {@link com.mongodb.DBCursor#skip(int)}, {@link com.mongodb.DBCursor#batchSize(int)} and {@link
* com.mongodb.DBCursor#setOptions(int)} on the {@code DBCursor} returned from {@link com.mongodb.DBCollection#find(DBObject,
* DBObject)}
*/
@Deprecated
public DBCursor find( DBObject query , DBObject fields , int numToSkip , int batchSize , int options ){
return find(query, fields, numToSkip, batchSize).addOption(options);
}
/**
* Finds objects from the database that match a query. A DBCursor object is returned, that can be iterated to go through the results.
*
* @param query query used to search
* @param fields the fields of matching objects to return
* @param numToSkip number of objects to skip
* @param batchSize the batch size. This option has a complex behavior, see {@link DBCursor#batchSize(int) }
* @return the cursor
* @throws MongoException
* @mongodb.driver.manual tutorial/query-documents/ Query
* @deprecated use {@link com.mongodb.DBCursor#skip(int)} and {@link com.mongodb.DBCursor#batchSize(int)} on the {@code DBCursor}
* returned from {@link com.mongodb.DBCollection#find(DBObject, DBObject)}
*/
@Deprecated
public DBCursor find( DBObject query , DBObject fields , int numToSkip , int batchSize ) {
DBCursor cursor = find(query, fields).skip(numToSkip).batchSize(batchSize);
return cursor;
}
// ------
/**
* Finds an object by its id.
* This compares the passed in value to the _id field of the document
*
* @param obj any valid object
* @return the object, if found, otherwise null
* @throws MongoException
*/
public DBObject findOne( Object obj ){
return findOne(obj, null);
}
/**
* Finds an object by its id.
* This compares the passed in value to the _id field of the document
*
* @param obj any valid object
* @param fields fields to return
* @return the object, if found, otherwise null
* @throws MongoException
* @mongodb.driver.manual tutorial/query-documents/ Query
*/
public DBObject findOne( Object obj, DBObject fields ){
Iterator<DBObject> iterator = find(new BasicDBObject("_id", obj), fields, 0, -1, 0, getOptions(), getReadPreference(), getDecoder());
return (iterator.hasNext() ? iterator.next() : null);
}
/**
* Atomically modify and return a single document. By default, the returned document does not include the modifications made on the
* update.
*
* @param query specifies the selection criteria for the modification
* @param fields a subset of fields to return
* @param sort determines which document the operation will modify if the query selects multiple documents
* @param remove when true, removes the selected document
* @param returnNew when true, returns the modified document rather than the original
* @param update the modifications to apply
* @param upsert when true, operation creates a new document if the query returns no documents
* @return the document as it was before the modifications, unless {@code returnNew} is true, in which case it returns the document
* after the changes were made
* @throws MongoException
* @mongodb.driver.manual reference/command/findAndModify/ Find and Modify
*/
public DBObject findAndModify(DBObject query, DBObject fields, DBObject sort, boolean remove, DBObject update, boolean returnNew, boolean upsert){
return findAndModify(query, fields, sort, remove, update, returnNew, upsert, 0L, MILLISECONDS);
}
/**
* Atomically modify and return a single document. By default, the returned document does not include the modifications made on the
* update.
*
* @param query specifies the selection criteria for the modification
* @param fields a subset of fields to return
* @param sort determines which document the operation will modify if the query selects multiple documents
* @param remove when {@code true}, removes the selected document
* @param returnNew when true, returns the modified document rather than the original
* @param update performs an update of the selected document
* @param upsert when true, operation creates a new document if the query returns no documents
* @param maxTime the maximum time that the server will allow this operation to execute before killing it. A non-zero value requires
* a server version >= 2.6
* @param maxTimeUnit the unit that maxTime is specified in
* @return the document as it was before the modifications, unless {@code returnNew} is true, in which case it returns the document
* after the changes were made
* @mongodb.driver.manual reference/command/findAndModify/ Find and Modify
* @since 2.12.0
*/
public DBObject findAndModify(final DBObject query, final DBObject fields, final DBObject sort,
final boolean remove, final DBObject update,
final boolean returnNew, final boolean upsert,
final long maxTime, final TimeUnit maxTimeUnit) {
BasicDBObject cmd = new BasicDBObject( "findandmodify", _name);
if (query != null && !query.keySet().isEmpty())
cmd.append( "query", query );
if (fields != null && !fields.keySet().isEmpty())
cmd.append( "fields", fields );
if (sort != null && !sort.keySet().isEmpty())
cmd.append( "sort", sort );
if (maxTime > 0) {
cmd.append("maxTimeMS", MILLISECONDS.convert(maxTime, maxTimeUnit));
}
if (remove)
cmd.append( "remove", remove );
else {
if (update != null && !update.keySet().isEmpty()) {
// if 1st key doesn't start with $, then object will be inserted as is, need to check it
String key = update.keySet().iterator().next();
if (key.charAt(0) != '$')
_checkObject(update, false, false);
cmd.append( "update", update );
}
if (returnNew)
cmd.append( "new", returnNew );
if (upsert)
cmd.append( "upsert", upsert );
}
if (remove && !(update == null || update.keySet().isEmpty() || returnNew))
throw new MongoException("FindAndModify: Remove cannot be mixed with the Update, or returnNew params!");
CommandResult res = this._db.command( cmd );
if (res.ok() || res.getErrorMessage().equals( "No matching object found" )) {
return replaceWithObjectClass((DBObject) res.get( "value" ));
}
res.throwOnError();
return null;
}
/**
* Doesn't yet handle internal classes properly, so this method only does something if object class is set but
* no internal classes are set.
*
* @param oldObj the original value from the command result
* @return replaced object if necessary, or oldObj
*/
private DBObject replaceWithObjectClass(DBObject oldObj) {
if (oldObj == null || getObjectClass() == null & _internalClass.isEmpty()) {
return oldObj;
}
DBObject newObj = instantiateObjectClassInstance();
for (String key : oldObj.keySet()) {
newObj.put(key, oldObj.get(key));
}
return newObj;
}
private DBObject instantiateObjectClassInstance() {
try {
return (DBObject) getObjectClass().newInstance();
} catch (InstantiationException e) {
throw new MongoInternalException("can't create instance of type " + getObjectClass(), e);
} catch (IllegalAccessException e) {
throw new MongoInternalException("can't create instance of type " + getObjectClass(), e);
}
}
/**
* Atomically modify and return a single document. By default, the returned document does not include the modifications made on the
* update. Calls {@link DBCollection#findAndModify(com.mongodb.DBObject, com.mongodb.DBObject, com.mongodb.DBObject, boolean,
* com.mongodb.DBObject, boolean, boolean)} with fields=null, remove=false, returnNew=false, upsert=false
*
* @param query specifies the selection criteria for the modification
* @param sort determines which document the operation will modify if the query selects multiple documents
* @param update the modifications to apply
* @return the document as it was before the modifications.
* @throws MongoException
* @mongodb.driver.manual reference/command/findAndModify/ Find and Modify
*/
public DBObject findAndModify( DBObject query , DBObject sort , DBObject update) {
return findAndModify( query, null, sort, false, update, false, false);
}
/**
* Atomically modify and return a single document. By default, the returned document does not include the modifications made on the
* update. Calls {@link DBCollection#findAndModify(com.mongodb.DBObject, com.mongodb.DBObject, com.mongodb.DBObject, boolean,
* com.mongodb.DBObject, boolean, boolean)} with fields=null, sort=null, remove=false, returnNew=false, upsert=false
*
* @param query specifies the selection criteria for the modification
* @param update the modifications to apply
* @return the document as it was before the modifications.
* @throws MongoException
* @mongodb.driver.manual reference/command/findAndModify/ Find and Modify
*/
public DBObject findAndModify( DBObject query , DBObject update ){
return findAndModify( query, null, null, false, update, false, false );
}
/**
* Atomically modify and return a single document. By default, the returned document does not include the modifications made on the
* update. Ccalls {@link DBCollection#findAndModify(com.mongodb.DBObject, com.mongodb.DBObject, com.mongodb.DBObject, boolean,
* com.mongodb.DBObject, boolean, boolean)} with fields=null, sort=null, remove=true, returnNew=false, upsert=false
*
* @param query specifies the selection criteria for the modification
* @return the document as it was before it was removed
* @throws MongoException
* @mongodb.driver.manual reference/command/findAndModify/ Find and Modify
*/
public DBObject findAndRemove( DBObject query ) {
return findAndModify( query, null, null, true, null, false, false );
}
// --- START INDEX CODE ---
/**
* Calls {@link DBCollection#createIndex(com.mongodb.DBObject, com.mongodb.DBObject)} with default index options
*
* @param keys a document that contains pairs with the name of the field or fields to index and order of the index
* @throws MongoException
* @mongodb.driver.manual /administration/indexes-creation/ Index Creation Tutorials
*/
public void createIndex( final DBObject keys ){
createIndex( keys , defaultOptions( keys ) );
}
/**
* Forces creation of an index on a set of fields, if one does not already exist.
*
* @param keys a document that contains pairs with the name of the field or fields to index and order of the index
* @param options a document that controls the creation of the index.
* @throws MongoException
* @mongodb.driver.manual /administration/indexes-creation/ Index Creation Tutorials
*/
public void createIndex( DBObject keys , DBObject options ){
createIndex( keys, options, getDBEncoder());
}
/**
* Forces creation of an index on a set of fields, if one does not already exist.
*
* @param keys a document that contains pairs with the name of the field or fields to index and order of the index
* @param options a document that controls the creation of the index.
* @param encoder specifies the encoder that used during operation
* @throws MongoException
* @mongodb.driver.manual /administration/indexes-creation/ Index Creation Tutorials
* @deprecated use {@link #createIndex(DBObject, com.mongodb.DBObject)} the encoder is not used.
*/
@Deprecated
public abstract void createIndex(DBObject keys, DBObject options, DBEncoder encoder);
/**
* Creates an ascending index on a field with default options, if one does not already exist.
*
* @param name name of field to index on
* @throws MongoException
* @mongodb.driver.manual /administration/indexes-creation/ Index Creation Tutorials
* @deprecated use {@link DBCollection#createIndex(DBObject)} instead
*/
@Deprecated
public void ensureIndex( final String name ){
ensureIndex( new BasicDBObject( name , 1 ) );
}
/**
* Calls {@link DBCollection#ensureIndex(com.mongodb.DBObject, com.mongodb.DBObject)} with default options
* @param keys an object with a key set of the fields desired for the index
* @throws MongoException
* @mongodb.driver.manual /administration/indexes-creation/ Index Creation Tutorials
*
* @deprecated use {@link DBCollection#createIndex(DBObject)} instead
*/
@Deprecated
public void ensureIndex( final DBObject keys ){
ensureIndex( keys , defaultOptions( keys ) );
}
/**
* Calls {@link DBCollection#ensureIndex(com.mongodb.DBObject, java.lang.String, boolean)} with unique=false
*
* @param keys fields to use for index
* @param name an identifier for the index
* @throws MongoException
* @mongodb.driver.manual /administration/indexes-creation/ Index Creation Tutorials
* @deprecated use {@link DBCollection#createIndex(DBObject, DBObject)} instead
*/
@Deprecated
public void ensureIndex( DBObject keys , String name ){
ensureIndex( keys , name , false );
}
/**
* Ensures an index on this collection (that is, the index will be created if it does not exist).
*
* @param keys fields to use for index
* @param name an identifier for the index. If null or empty, the default name will be used.
* @param unique if the index should be unique
* @throws MongoException
* @mongodb.driver.manual /administration/indexes-creation/ Index Creation Tutorials
* @deprecated use {@link DBCollection#createIndex(DBObject, DBObject)} instead
*/
@Deprecated
public void ensureIndex( DBObject keys , String name , boolean unique ){
DBObject options = defaultOptions( keys );
if (name != null && name.length()>0)
options.put( "name" , name );
if ( unique )
options.put( "unique" , Boolean.TRUE );
ensureIndex( keys , options );
}
/**
* Creates an index on a set of fields, if one does not already exist.
*
* @param keys an object with a key set of the fields desired for the index
* @param optionsIN options for the index (name, unique, etc)
* @throws MongoException
* @mongodb.driver.manual /administration/indexes-creation/ Index Creation Tutorials
* @deprecated use {@link DBCollection#createIndex(DBObject, DBObject)} instead
*/
@Deprecated
public void ensureIndex( final DBObject keys , final DBObject optionsIN ){
if ( checkReadOnly( false ) ) return;
final DBObject options = defaultOptions( keys );
for ( String k : optionsIN.keySet() )
options.put( k , optionsIN.get( k ) );
final String name = options.get( "name" ).toString();
if ( _createdIndexes.contains( name ) )
return;
createIndex( keys , options );
_createdIndexes.add( name );
}
/**
* Clears all indices that have not yet been applied to this collection.
* @deprecated This will be removed in 3.0
*/
@Deprecated
public void resetIndexCache(){
_createdIndexes.clear();
}
DBObject defaultOptions( DBObject keys ){
DBObject o = new BasicDBObject();
o.put( "name" , genIndexName( keys ) );
o.put( "ns" , _fullName );
return o;
}
/**
* Convenience method to generate an index name from the set of fields it is over.
* @param keys the names of the fields used in this index
* @return a string representation of this index's fields
*
* @deprecated This method is NOT a part of public API and will be dropped in 3.x versions.
*/
@Deprecated
public static String genIndexName( DBObject keys ){
StringBuilder name = new StringBuilder();
for ( String s : keys.keySet() ){
if ( name.length() > 0 )
name.append( '_' );
name.append( s ).append( '_' );
Object val = keys.get( s );
if ( val instanceof Number || val instanceof String )
name.append( val.toString().replace( ' ', '_' ) );
}
return name.toString();
}
// --- END INDEX CODE ---
/**
* Set hint fields for this collection (to optimize queries).
* @param lst a list of {@code DBObject}s to be used as hints
*/
public void setHintFields( List<DBObject> lst ){
_hintFields = lst;
}
/**
* Get hint fields for this collection (used to optimize queries).
* @return a list of {@code DBObject} to be used as hints.
*/
protected List<DBObject> getHintFields() {
return _hintFields;
}
/**
* Queries for an object in this collection.
*
* @param ref A document outlining the search query
* @return an iterator over the results
* @mongodb.driver.manual tutorial/query-documents/ Query
*/
public DBCursor find( DBObject ref ){
return new DBCursor( this, ref, null, getReadPreference());
}
/**
* Queries for an object in this collection.
* <p>
* An empty DBObject will match every document in the collection.
* Regardless of fields specified, the _id fields are always returned.
* </p>
* <p>
* An example that returns the "x" and "_id" fields for every document
* in the collection that has an "x" field:
* </p>
* <pre>
* {@code
* BasicDBObject keys = new BasicDBObject();
* keys.put("x", 1);
*
* DBCursor cursor = collection.find(new BasicDBObject(), keys);}
* </pre>
*
* @param ref object for which to search
* @param keys fields to return
* @return a cursor to iterate over results
* @mongodb.driver.manual tutorial/query-documents/ Query
*/
public DBCursor find( DBObject ref , DBObject keys ){
return new DBCursor( this, ref, keys, getReadPreference());
}
/**
* Queries for all objects in this collection.
*
* @return a cursor which will iterate over every object
* @mongodb.driver.manual tutorial/query-documents/ Query
*/
public DBCursor find(){
return new DBCursor( this, null, null, getReadPreference());
}
/**
* Returns a single object from this collection.
*
* @return the object found, or {@code null} if the collection is empty
* @throws MongoException
* @mongodb.driver.manual tutorial/query-documents/ Query
*/
public DBObject findOne(){
return findOne( new BasicDBObject() );
}
/**
* Returns a single object from this collection matching the query.
* @param o the query object
* @return the object found, or {@code null} if no such object exists
* @throws MongoException
* @mongodb.driver.manual tutorial/query-documents/ Query
*/
public DBObject findOne( DBObject o ){
return findOne( o, null, null, getReadPreference());
}
/**
* Returns a single object from this collection matching the query.
* @param o the query object
* @param fields fields to return
* @return the object found, or {@code null} if no such object exists
* @throws MongoException
* @mongodb.driver.manual tutorial/query-documents/ Query
*/
public DBObject findOne( DBObject o, DBObject fields ) {
return findOne( o, fields, null, getReadPreference());
}
/**
* Returns a single object from this collection matching the query.
* @param o the query object
* @param fields fields to return
* @param orderBy fields to order by
* @return the object found, or {@code null} if no such object exists
* @throws MongoException
* @mongodb.driver.manual tutorial/query-documents/ Query
*/
public DBObject findOne( DBObject o, DBObject fields, DBObject orderBy){
return findOne(o, fields, orderBy, getReadPreference());
}
/**
* Get a single document from collection.
*
* @param o the selection criteria using query operators.
* @param fields specifies which fields MongoDB will return from the documents in the result set.
* @param readPref {@link ReadPreference} to be used for this operation
* @return A document that satisfies the query specified as the argument to this method, or {@code null} if no such object exists
* @throws MongoException
* @mongodb.driver.manual tutorial/query-documents/ Query
*/
public DBObject findOne( DBObject o, DBObject fields, ReadPreference readPref ){
return findOne(o, fields, null, readPref);
}
/**
* Get a single document from collection.
*
* @param o the selection criteria using query operators.
* @param fields specifies which projection MongoDB will return from the documents in the result set.
* @param orderBy A document whose fields specify the attributes on which to sort the result set.
* @param readPref {@code ReadPreference} to be used for this operation
* @return A document that satisfies the query specified as the argument to this method, or {@code null} if no such object exists
* @throws MongoException
* @mongodb.driver.manual tutorial/query-documents/ Query
*/
public DBObject findOne(DBObject o, DBObject fields, DBObject orderBy, ReadPreference readPref) {
return findOne(o, fields, orderBy, readPref, 0, MILLISECONDS);
}
/**
* Get a single document from collection.
*
* @param o the selection criteria using query operators.
* @param fields specifies which projection MongoDB will return from the documents in the result set.
* @param orderBy A document whose fields specify the attributes on which to sort the result set.
* @param readPref {@code ReadPreference} to be used for this operation
* @param maxTime the maximum time that the server will allow this operation to execute before killing it
* @param maxTimeUnit the unit that maxTime is specified in
* @return A document that satisfies the query specified as the argument to this method.
* @mongodb.driver.manual tutorial/query-documents/ Query
* @since 2.12.0
*/
DBObject findOne(DBObject o, DBObject fields, DBObject orderBy, ReadPreference readPref,
long maxTime, TimeUnit maxTimeUnit) {
QueryOpBuilder queryOpBuilder = new QueryOpBuilder().addQuery(o).addOrderBy(orderBy)
.addMaxTimeMS(MILLISECONDS.convert(maxTime, maxTimeUnit));
if (getDB().getMongo().isMongosConnection()) {
queryOpBuilder.addReadPreference(readPref);
}
Iterator<DBObject> i = find(queryOpBuilder.get(), fields, 0, -1, 0, getOptions(), readPref, getDecoder());
DBObject obj = (i.hasNext() ? i.next() : null);
if ( obj != null && ( fields != null && fields.keySet().size() > 0 ) ){
obj.markAsPartialObject();
}
return obj;
}
// Only create a new decoder if there is a decoder factory explicitly set on the collection. Otherwise return null
// so that DBPort will use a cached decoder from the default factory.
DBDecoder getDecoder() {
return getDBDecoderFactory() != null ? getDBDecoderFactory().create() : null;
}
// Only create a new encoder if there is an encoder factory explicitly set on the collection. Otherwise return null
// to allow DB to create its own or use a cached one.
private DBEncoder getDBEncoder() {
return getDBEncoderFactory() != null ? getDBEncoderFactory().create() : null;
}
/**
* calls {@link DBCollection#apply(com.mongodb.DBObject, boolean)} with ensureID=true
* @param o {@code DBObject} to which to add fields
* @return the modified parameter object
*/
public Object apply( DBObject o ){
return apply( o , true );
}
/**
* calls {@link DBCollection#doapply(com.mongodb.DBObject)}, optionally adding an automatic _id field
* @param jo object to add fields to
* @param ensureID whether to add an {@code _id} field
* @return the modified object {@code o}
*/
public Object apply( DBObject jo , boolean ensureID ){
Object id = jo.get("_id");
if (ensureID && id == null) {
id = ObjectId.get();
jo.put("_id", id);
}
doapply(jo);
return id;
}
/**
* Update an existing document or insert a document depending on the parameter. If the document does not contain an '_id' field, then
* the method performs an insert with the specified fields in the document as well as an '_id' field with a unique objectid value. If
* the document contains an '_id' field, then the method performs an upsert querying the collection on the '_id' field: <ul> <li>If a
* document does not exist with the specified '_id' value, the method performs an insert with the specified fields in the document.</li>
* <li>If a document exists with the specified '_id' value, the method performs an update, replacing all field in the existing record
* with the fields from the document.</li> </ul>. Calls {@link DBCollection#save(com.mongodb.DBObject, com.mongodb.WriteConcern)} with
* default WriteConcern
*
* @param jo {@link DBObject} to save to the collection.
* @return the result of the operation
* @throws MongoException if the operation fails
* @mongodb.driver.manual tutorial/modify-documents/#modify-a-document-with-save-method Save
*/
public WriteResult save( DBObject jo ){
return save(jo, getWriteConcern());
}
/**
* Update an existing document or insert a document depending on the parameter. If the document does not contain an '_id' field, then
* the method performs an insert with the specified fields in the document as well as an '_id' field with a unique objectid value. If
* the document contains an '_id' field, then the method performs an upsert querying the collection on the '_id' field: <ul> <li>If a
* document does not exist with the specified '_id' value, the method performs an insert with the specified fields in the document.</li>
* <li>If a document exists with the specified '_id' value, the method performs an update, replacing all field in the existing record
* with the fields from the document.</li> </ul>
*
* @param jo {@link DBObject} to save to the collection.
* @param concern {@code WriteConcern} to be used during operation
* @return the result of the operation
* @throws MongoException if the operation fails
* @mongodb.driver.manual tutorial/modify-documents/#modify-a-document-with-save-method Save
*/
public WriteResult save( DBObject jo, WriteConcern concern ){
if ( checkReadOnly( true ) )
return null;
_checkObject( jo , false , false );
Object id = jo.get( "_id" );
if (id == null || (id instanceof ObjectId && ((ObjectId) id).isNew())) {
if (id != null) {
((ObjectId) id).notNew();
}
if (concern == null) {
return insert(jo);
} else {
return insert(jo, concern);
}
}
DBObject q = new BasicDBObject();
q.put("_id", id);
if (concern == null) {
return update(q, jo, true, false);
} else {
return update(q, jo, true, false, concern);
}
}
// ---- DB COMMANDS ----
/**
* Drops all indices from this collection
* @throws MongoException
*/
public void dropIndexes(){
dropIndexes( "*" );
}
/**
* Drops an index from this collection
* @param name the index name
* @throws MongoException
*/
public void dropIndexes( String name ){
DBObject cmd = BasicDBObjectBuilder.start()
.add( "deleteIndexes" , getName() )
.add( "index" , name )
.get();