signature:
public class DBCollection { /** * Get the count of documents in collection that would match a criteria .
 * @ param query specifies the selection criteria
 * @ param projection this is ignored
 * @ param limit limit the count to this value
 * @ param skip number of documents to skip
 * @ return the number of documents that matches selection criteria
 * @ throws MongoException if the operation failed
 * @ mongodb . driver . manual reference / command / count / Count
 * @ deprecated Prefer { @ link # count ( DBObject , DBCollectionCountOptions ) } */
@ Deprecated public long getCount ( @ Nullable final DBObject query , @ Nullable final DBObject projection , final long limit , final long skip ) { } }

implementation: return getCount ( query , projection , limit , skip , getReadPreference ( ) ) ;


signature:
public class DBCollection { /** * Get the count of documents in collection that would match a criteria .
 * @ param query specifies the selection criteria
 * @ param projection this is ignored
 * @ param limit limit the count to this value
 * @ param skip number of documents to skip
 * @ param readPreference { @ link ReadPreference } to be used for this operation
 * @ return the number of documents that matches selection criteria
 * @ throws MongoException if the operation failed
 * @ mongodb . driver . manual reference / command / count / Count
 * @ deprecated Prefer { @ link # count ( DBObject , DBCollectionCountOptions ) } */
@ Deprecated public long getCount ( @ Nullable final DBObject query , @ Nullable final DBObject projection , final long limit , final long skip , final ReadPreference readPreference ) { } }

implementation: return getCount ( query , new DBCollectionCountOptions ( ) . limit ( limit ) . skip ( skip ) . readPreference ( readPreference ) ) ;


signature:
public class DBCollection { /** * Get the count of documents in collection that would match a criteria .
 * @ param query specifies the selection criteria
 * @ param options the options for the count operation .
 * @ return the number of documents that matches selection criteria
 * @ throws MongoException if the operation failed
 * @ mongodb . driver . manual reference / command / count / Count
 * @ since 3.4 */
public long getCount ( @ Nullable final DBObject query , final DBCollectionCountOptions options ) { } }

implementation: notNull ( "countOptions" , options ) ; CountOperation operation = new CountOperation ( getNamespace ( ) ) . skip ( options . getSkip ( ) ) . limit ( options . getLimit ( ) ) . maxTime ( options . getMaxTime ( MILLISECONDS ) , MILLISECONDS ) . collation ( options . getCollation ( ) ) . retryReads ( retryReads ) ; if ( query != null ) { operation . filter ( wrap ( query ) ) ; } DBObject hint = options . getHint ( ) ; if ( hint != null ) { operation . hint ( wrap ( hint ) ) ; } else { String hintString = options . getHintString ( ) ; if ( hintString != null ) { operation . hint ( new BsonString ( hintString ) ) ; } } ReadPreference optionsReadPreference = options . getReadPreference ( ) ; ReadConcern optionsReadConcern = options . getReadConcern ( ) ; return executor . execute ( operation , optionsReadPreference != null ? optionsReadPreference : getReadPreference ( ) , optionsReadConcern != null ? optionsReadConcern : getReadConcern ( ) ) ;


signature:
public class DBCollection { /** * Change the name of an existing collection .
 * @ param newName specifies the new name of the collection
 * @ param dropTarget If { @ code true } , mongod will drop the collection with the target name if it exists
 * @ return the collection with new name
 * @ throws MongoException if target is the name of an existing collection and { @ code dropTarget = false } .
 * @ mongodb . driver . manual reference / command / renameCollection / Rename Collection */
public DBCollection rename ( final String newName , final boolean dropTarget ) { } }

implementation: try { executor . execute ( new RenameCollectionOperation ( getNamespace ( ) , new MongoNamespace ( getNamespace ( ) . getDatabaseName ( ) , newName ) , getWriteConcern ( ) ) . dropTarget ( dropTarget ) , getReadConcern ( ) ) ; return getDB ( ) . getCollection ( newName ) ; } catch ( MongoWriteConcernException e ) { throw createWriteConcernException ( e ) ; }


signature:
public class DBCollection { /** * Group documents in a collection by the specified key and performs simple aggregation functions such as computing counts and sums .
 * This is analogous to a { @ code SELECT . . . GROUP BY } statement in SQL .
 * @ param key specifies one or more document fields to group
 * @ param cond specifies the selection criteria to determine which documents in the collection to process
 * @ param initial initializes the aggregation result document
 * @ param reduce specifies an $ reduce function , that operates on the documents during the grouping operation
 * @ return a document with the grouped records as well as the command meta - data
 * @ mongodb . driver . manual reference / command / group / Group Command
 * @ deprecated The group command was deprecated in MongoDB 3.4 */
@ Deprecated public DBObject group ( final DBObject key , final DBObject cond , final DBObject initial , final String reduce ) { } }

implementation: return group ( key , cond , initial , reduce , null ) ;


signature:
public class DBCollection { /** * Group documents in a collection by the specified key and performs simple aggregation functions such as computing counts and sums .
 * This is analogous to a { @ code SELECT . . . GROUP BY } statement in SQL .
 * @ param key specifies one or more document fields to group
 * @ param cond specifies the selection criteria to determine which documents in the collection to process
 * @ param initial initializes the aggregation result document
 * @ param reduce specifies an $ reduce Javascript function , that operates on the documents during the grouping operation
 * @ param finalize specifies a Javascript function that runs each item in the result set before final value will be returned
 * @ return a document with the grouped records as well as the command meta - data
 * @ mongodb . driver . manual reference / command / group / Group Command
 * @ deprecated The group command was deprecated in MongoDB 3.4 */
@ Deprecated public DBObject group ( final DBObject key , final DBObject cond , final DBObject initial , final String reduce , @ Nullable final String finalize ) { } }

implementation: return group ( key , cond , initial , reduce , finalize , getReadPreference ( ) ) ;


signature:
public class DBCollection { /** * Group documents in a collection by the specified key and performs simple aggregation functions such as computing counts and sums .
 * This is analogous to a { @ code SELECT . . . GROUP BY } statement in SQL .
 * @ param key specifies one or more document fields to group
 * @ param cond specifies the selection criteria to determine which documents in the collection to process
 * @ param initial initializes the aggregation result document
 * @ param reduce specifies an $ reduce Javascript function , that operates on the documents during the grouping operation
 * @ param finalize specifies a Javascript function that runs each item in the result set before final value will be returned
 * @ param readPreference { @ link ReadPreference } to be used for this operation
 * @ return a document with the grouped records as well as the command meta - data
 * @ mongodb . driver . manual reference / command / group / Group Command
 * @ deprecated The group command was deprecated in MongoDB 3.4 */
@ Deprecated public DBObject group ( final DBObject key , final DBObject cond , final DBObject initial , final String reduce , @ Nullable final String finalize , final ReadPreference readPreference ) { } }

implementation: return group ( new GroupCommand ( this , key , cond , initial , reduce , finalize ) , readPreference ) ;


signature:
public class DBCollection { /** * Group documents in a collection by the specified key and performs simple aggregation functions such as computing counts and sums .
 * This is analogous to a { @ code SELECT . . . GROUP BY } statement in SQL .
 * @ param cmd the group command
 * @ param readPreference { @ link ReadPreference } to be used for this operation
 * @ return a document with the grouped records as well as the command meta - data
 * @ mongodb . driver . manual reference / command / group / Group Command
 * @ deprecated The group command was deprecated in MongoDB 3.4 */
@ Deprecated public DBObject group ( final GroupCommand cmd , final ReadPreference readPreference ) { } }

implementation: return toDBList ( executor . execute ( cmd . toOperation ( getNamespace ( ) , getDefaultDBObjectCodec ( ) , retryReads ) , readPreference , getReadConcern ( ) ) ) ;


signature:
public class DBCollection { /** * Find the distinct values for a specified field across a collection and returns the results in an array .
 * @ param fieldName Specifies the field for which to return the distinct values
 * @ param readPreference { @ link ReadPreference } to be used for this operation
 * @ return a List of the distinct values
 * @ mongodb . driver . manual reference / command / distinct Distinct Command */
public List distinct ( final String fieldName , final ReadPreference readPreference ) { } }

implementation: return distinct ( fieldName , new BasicDBObject ( ) , readPreference ) ;


signature:
public class DBCollection { /** * Find the distinct values for a specified field across a collection and returns the results in an array .
 * @ param fieldName Specifies the field for which to return the distinct values
 * @ param query specifies the selection query to determine the subset of documents from which to retrieve the distinct values
 * @ return an array of the distinct values
 * @ mongodb . driver . manual reference / command / distinct Distinct Command */
public List distinct ( final String fieldName , final DBObject query ) { } }

implementation: return distinct ( fieldName , query , getReadPreference ( ) ) ;


signature:
public class DBCollection { /** * Find the distinct values for a specified field across a collection and returns the results in an array .
 * @ param fieldName Specifies the field for which to return the distinct values
 * @ param query specifies the selection query to determine the subset of documents from which to retrieve the distinct values
 * @ param readPreference { @ link ReadPreference } to be used for this operation
 * @ return A { @ code List } of the distinct values
 * @ mongodb . driver . manual reference / command / distinct Distinct Command */
public List distinct ( final String fieldName , final DBObject query , final ReadPreference readPreference ) { } }

implementation: return distinct ( fieldName , new DBCollectionDistinctOptions ( ) . filter ( query ) . readPreference ( readPreference ) ) ;


signature:
public class DBCollection { /** * Find the distinct values for a specified field across a collection and returns the results in an array .
 * @ param fieldName Specifies the field for which to return the distinct values
 * @ param options the options to apply for this operation
 * @ return A { @ code List } of the distinct values
 * @ mongodb . driver . manual reference / command / distinct Distinct Command
 * @ since 3.4 */
@ SuppressWarnings ( "unchecked" ) public List distinct ( final String fieldName , final DBCollectionDistinctOptions options ) { } }

implementation: notNull ( "fieldName" , fieldName ) ; return new MongoIterableImpl < BsonValue > ( null , executor , options . getReadConcern ( ) != null ? options . getReadConcern ( ) : getReadConcern ( ) , options . getReadPreference ( ) != null ? options . getReadPreference ( ) : getReadPreference ( ) , retryReads ) { @ Override public ReadOperation < BatchCursor < BsonValue > > asReadOperation ( ) { return new DistinctOperation < BsonValue > ( getNamespace ( ) , fieldName , new BsonValueCodec ( ) ) . filter ( wrapAllowNull ( options . getFilter ( ) ) ) . collation ( options . getCollation ( ) ) . retryReads ( retryReads ) ; } } . map ( new Function < BsonValue , Object > ( ) { @ Override public Object apply ( final BsonValue bsonValue ) { if ( bsonValue == null ) { return null ; } BsonDocument document = new BsonDocument ( "value" , bsonValue ) ; DBObject obj = getDefaultDBObjectCodec ( ) . decode ( new BsonDocumentReader ( document ) , DecoderContext . builder ( ) . build ( ) ) ; return obj . get ( "value" ) ; } } ) . into ( new ArrayList < Object > ( ) ) ;


signature:
public class DBCollection { /** * Allows you to run map - reduce aggregation operations over a collection and saves to a named collection .
 * @ param map a JavaScript function that associates or " maps " a value with a key and emits the key and value pair .
 * @ param reduce a JavaScript function that " reduces " to a single object all the values associated with a particular key .
 * @ param outputTarget specifies the location of the result of the map - reduce operation .
 * @ param outputType specifies the type of job output
 * @ param query specifies the selection criteria using query operators for determining the documents input to the map
 * function .
 * @ param readPreference the read preference specifying where to run the query . Only applied for Inline output type
 * @ return a MapReduceOutput which contains the results of this map reduce operation
 * @ mongodb . driver . manual core / map - reduce / Map - Reduce */
public MapReduceOutput mapReduce ( final String map , final String reduce , final String outputTarget , final MapReduceCommand . OutputType outputType , final DBObject query , final ReadPreference readPreference ) { } }

implementation: MapReduceCommand command = new MapReduceCommand ( this , map , reduce , outputTarget , outputType , query ) ; command . setReadPreference ( readPreference ) ; return mapReduce ( command ) ;


signature:
public class DBCollection { /** * Allows you to run map - reduce aggregation operations over a collection .
 * @ param command specifies the details of the Map Reduce operation to perform
 * @ return a MapReduceOutput containing the results of the map reduce operation
 * @ mongodb . driver . manual core / map - reduce / Map - Reduce */
public MapReduceOutput mapReduce ( final MapReduceCommand command ) { } }

implementation: ReadPreference readPreference = command . getReadPreference ( ) == null ? getReadPreference ( ) : command . getReadPreference ( ) ; Map < String , Object > scope = command . getScope ( ) ; Boolean jsMode = command . getJsMode ( ) ; if ( command . getOutputType ( ) == MapReduceCommand . OutputType . INLINE ) { MapReduceWithInlineResultsOperation < DBObject > operation = new MapReduceWithInlineResultsOperation < DBObject > ( getNamespace ( ) , new BsonJavaScript ( command . getMap ( ) ) , new BsonJavaScript ( command . getReduce ( ) ) , getDefaultDBObjectCodec ( ) ) . filter ( wrapAllowNull ( command . getQuery ( ) ) ) . limit ( command . getLimit ( ) ) . maxTime ( command . getMaxTime ( MILLISECONDS ) , MILLISECONDS ) . jsMode ( jsMode == null ? false : jsMode ) . sort ( wrapAllowNull ( command . getSort ( ) ) ) . verbose ( command . isVerbose ( ) ) . collation ( command . getCollation ( ) ) ; if ( scope != null ) { operation . scope ( wrap ( new BasicDBObject ( scope ) ) ) ; } if ( command . getFinalize ( ) != null ) { operation . finalizeFunction ( new BsonJavaScript ( command . getFinalize ( ) ) ) ; } MapReduceBatchCursor < DBObject > executionResult = executor . execute ( operation , readPreference , getReadConcern ( ) ) ; return new MapReduceOutput ( command . toDBObject ( ) , executionResult ) ; } else { String action ; switch ( command . getOutputType ( ) ) { case REPLACE : action = "replace" ; break ; case MERGE : action = "merge" ; break ; case REDUCE : action = "reduce" ; break ; default : throw new IllegalArgumentException ( "Unexpected output type" ) ; } MapReduceToCollectionOperation operation = new MapReduceToCollectionOperation ( getNamespace ( ) , new BsonJavaScript ( command . getMap ( ) ) , new BsonJavaScript ( command . getReduce ( ) ) , command . getOutputTarget ( ) , getWriteConcern ( ) ) . filter ( wrapAllowNull ( command . getQuery ( ) ) ) . limit ( command . getLimit ( ) ) . maxTime ( command . getMaxTime ( MILLISECONDS ) , MILLISECONDS ) . jsMode ( jsMode == null ? false : jsMode ) . sort ( wrapAllowNull ( command . getSort ( ) ) ) . verbose ( command . isVerbose ( ) ) . action ( action ) . databaseName ( command . getOutputDB ( ) ) . bypassDocumentValidation ( command . getBypassDocumentValidation ( ) ) . collation ( command . getCollation ( ) ) ; if ( scope != null ) { operation . scope ( wrap ( new BasicDBObject ( scope ) ) ) ; } if ( command . getFinalize ( ) != null ) { operation . finalizeFunction ( new BsonJavaScript ( command . getFinalize ( ) ) ) ; } try { MapReduceStatistics mapReduceStatistics = executor . execute ( operation , getReadConcern ( ) ) ; DBCollection mapReduceOutputCollection = getMapReduceOutputCollection ( command ) ; DBCursor executionResult = mapReduceOutputCollection . find ( ) ; return new MapReduceOutput ( command . toDBObject ( ) , executionResult , mapReduceStatistics , mapReduceOutputCollection ) ; } catch ( MongoWriteConcernException e ) { throw createWriteConcernException ( e ) ; } }


signature:
public class DBCollection { /** * Method implements aggregation framework .
 * @ param firstOp requisite first operation to be performed in the aggregation pipeline
 * @ param additionalOps additional operations to be performed in the aggregation pipeline
 * @ return the aggregation operation ' s result set
 * @ mongodb . driver . manual core / aggregation - pipeline / Aggregation
 * @ mongodb . server . release 2.2
 * @ deprecated Use { @ link # aggregate ( List , AggregationOptions ) } instead */
@ Deprecated @ SuppressWarnings ( "unchecked" ) public AggregationOutput aggregate ( final DBObject firstOp , final DBObject ... additionalOps ) { } }

implementation: List < DBObject > pipeline = new ArrayList < DBObject > ( ) ; pipeline . add ( firstOp ) ; Collections . addAll ( pipeline , additionalOps ) ; return aggregate ( pipeline ) ;


signature:
public class DBCollection { /** * Method implements aggregation framework .
 * @ param pipeline operations to be performed in the aggregation pipeline
 * @ param readPreference the read preference specifying where to run the query
 * @ return the aggregation ' s result set
 * @ mongodb . driver . manual core / aggregation - pipeline / Aggregation
 * @ mongodb . server . release 2.2
 * @ deprecated Use { @ link # aggregate ( List , AggregationOptions , ReadPreference ) } ) } instead */
@ Deprecated @ SuppressWarnings ( "unchecked" ) public AggregationOutput aggregate ( final List < ? extends DBObject > pipeline , final ReadPreference readPreference ) { } }

implementation: Cursor cursor = aggregate ( pipeline , AggregationOptions . builder ( ) . build ( ) , readPreference , false ) ; if ( cursor == null ) { return new AggregationOutput ( Collections . < DBObject > emptyList ( ) ) ; } else { List < DBObject > results = new ArrayList < DBObject > ( ) ; while ( cursor . hasNext ( ) ) { results . add ( cursor . next ( ) ) ; } return new AggregationOutput ( results ) ; }


signature:
public class DBCollection { /** * Method implements aggregation framework .
 * @ param pipeline operations to be performed in the aggregation pipeline
 * @ param options options to apply to the aggregation
 * @ return the aggregation operation ' s result set
 * @ mongodb . driver . manual core / aggregation - pipeline / Aggregation
 * @ mongodb . server . release 2.2 */
public Cursor aggregate ( final List < ? extends DBObject > pipeline , final AggregationOptions options ) { } }

implementation: return aggregate ( pipeline , options , getReadPreference ( ) ) ;


signature:
public class DBCollection { /** * Method implements aggregation framework .
 * @ param pipeline operations to be performed in the aggregation pipeline
 * @ param options options to apply to the aggregation
 * @ param readPreference { @ link ReadPreference } to be used for this operation
 * @ return the aggregation operation ' s result set
 * @ mongodb . driver . manual core / aggregation - pipeline / Aggregation
 * @ mongodb . server . release 2.2 */
public Cursor aggregate ( final List < ? extends DBObject > pipeline , final AggregationOptions options , final ReadPreference readPreference ) { } }

implementation: Cursor cursor = aggregate ( pipeline , options , readPreference , true ) ; if ( cursor == null ) { throw new MongoInternalException ( "cursor can not be null in this context" ) ; } return cursor ;


signature:
public class DBCollection { /** * Return the explain plan for the aggregation pipeline .
 * @ param pipeline the aggregation pipeline to explain
 * @ param options the options to apply to the aggregation
 * @ return the command result . The explain output may change from release to release , so best to simply log this .
 * @ mongodb . driver . manual core / aggregation - pipeline / Aggregation
 * @ mongodb . driver . manual reference / operator / meta / explain / Explain query
 * @ mongodb . server . release 2.6 */
public CommandResult explainAggregate ( final List < ? extends DBObject > pipeline , final AggregationOptions options ) { } }

implementation: AggregateOperation < BsonDocument > operation = new AggregateOperation < BsonDocument > ( getNamespace ( ) , preparePipeline ( pipeline ) , new BsonDocumentCodec ( ) ) . maxTime ( options . getMaxTime ( MILLISECONDS ) , MILLISECONDS ) . allowDiskUse ( options . getAllowDiskUse ( ) ) . collation ( options . getCollation ( ) ) . retryReads ( retryReads ) ; return new CommandResult ( executor . execute ( operation . asExplainableOperation ( ExplainVerbosity . QUERY_PLANNER ) , primaryPreferred ( ) , getReadConcern ( ) ) ) ;


signature:
public class DBCollection { /** * < p > Return a list of cursors over the collection that can be used to scan it in parallel . < / p >
 * < p > Note : As of MongoDB 2.6 , this method will work against a mongod , but not a mongos . < / p >
 * @ param options the parallel scan options
 * @ return a list of cursors , whose size may be less than the number requested
 * @ mongodb . driver . manual reference / command / parallelCollectionScan / Parallel Collection Scan
 * @ mongodb . server . release 2.6
 * @ since 2.12
 * @ deprecated the parallelCollectionScan command will be removed in MongoDB 4.2 */
@ Deprecated public List < Cursor > parallelScan ( final ParallelScanOptions options ) { } }

implementation: List < Cursor > cursors = new ArrayList < Cursor > ( ) ; ParallelCollectionScanOperation < DBObject > operation = new ParallelCollectionScanOperation < DBObject > ( getNamespace ( ) , options . getNumCursors ( ) , objectCodec ) . batchSize ( options . getBatchSize ( ) ) . retryReads ( retryReads ) ; ReadPreference readPreferenceFromOptions = options . getReadPreference ( ) ; List < BatchCursor < DBObject > > mongoCursors = executor . execute ( operation , readPreferenceFromOptions != null ? readPreferenceFromOptions : getReadPreference ( ) , getReadConcern ( ) ) ; for ( BatchCursor < DBObject > mongoCursor : mongoCursors ) { cursors . add ( new MongoCursorAdapter ( new MongoBatchCursorAdapter < DBObject > ( mongoCursor ) ) ) ; } return cursors ;


signature:
public class DBCollection { /** * 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 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 if the operation failed
 * @ mongodb . driver . manual / administration / indexes - creation / Index Creation Tutorials */
public void createIndex ( final DBObject keys , @ Nullable final String name , final boolean unique ) { } }

implementation: DBObject options = new BasicDBObject ( ) ; if ( name != null && name . length ( ) > 0 ) { options . put ( "name" , name ) ; } if ( unique ) { options . put ( "unique" , Boolean . TRUE ) ; } createIndex ( keys , options ) ;


signature:
public class DBCollection { /** * Creates an index on the field specified , if that index does not already exist .
 * < p > Prior to MongoDB 3.0 the dropDups option could be used with unique indexes allowing documents with duplicate values to be dropped
 * when building the index . Later versions of MongoDB will silently ignore this setting . < / p >
 * @ 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 .
 * @ mongodb . driver . manual / administration / indexes - creation / Index Creation Tutorials */
public void createIndex ( final DBObject keys , final DBObject options ) { } }

implementation: try { executor . execute ( createIndexOperation ( keys , options ) , getReadConcern ( ) ) ; } catch ( MongoWriteConcernException e ) { throw createWriteConcernException ( e ) ; }


signature:
public class DBCollection { /** * 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 sort determines which document the operation will modify if the query selects multiple documents
 * @ param update the modifications to apply
 * @ return pre - modification document
 * @ throws WriteConcernException if the write failed due some other failure specific to the update command
 * @ throws MongoException if the operation failed for some other reason
 * @ mongodb . driver . manual reference / command / findAndModify / Find and Modify */
@ Nullable public DBObject findAndModify ( @ Nullable final DBObject query , @ Nullable final DBObject sort , final DBObject update ) { } }

implementation: return findAndModify ( query , null , sort , false , update , false , false ) ;


signature:
public class DBCollection { /** * Atomically remove and return a single document . The returned document is the original document before removal .
 * @ param query specifies the selection criteria for the modification
 * @ return the document as it was before the modifications
 * @ throws WriteConcernException if the write failed due some other failure specific to the update command
 * @ throws MongoException if the operation failed for some other reason
 * @ mongodb . driver . manual reference / command / findAndModify / Find and Modify */
@ Nullable public DBObject findAndRemove ( @ Nullable final DBObject query ) { } }

implementation: return findAndModify ( query , null , null , true , null , false , false ) ;


signature:
public class DBCollection { /** * 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 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 WriteConcernException if the write failed due some other failure specific to the update command
 * @ throws MongoException if the operation failed for some other reason
 * @ mongodb . driver . manual reference / command / findAndModify / Find and Modify */
@ Nullable public DBObject findAndModify ( @ Nullable final DBObject query , @ Nullable final DBObject fields , @ Nullable final DBObject sort , final boolean remove , @ Nullable final DBObject update , final boolean returnNew , final boolean upsert ) { } }

implementation: return findAndModify ( query , fields , sort , remove , update , returnNew , upsert , 0L , MILLISECONDS ) ;


signature:
public class DBCollection { /** * 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
 * @ 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 & gt ; = 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
 * @ throws WriteConcernException if the write failed due some other failure specific to the update command
 * @ throws MongoException if the operation failed for some other reason
 * @ mongodb . driver . manual reference / command / findAndModify / Find and Modify
 * @ since 2.12.0 */
@ Nullable public DBObject findAndModify ( @ Nullable final DBObject query , @ Nullable final DBObject fields , @ Nullable final DBObject sort , final boolean remove , @ Nullable final DBObject update , final boolean returnNew , final boolean upsert , final long maxTime , final TimeUnit maxTimeUnit ) { } }

implementation: return findAndModify ( query , fields , sort , remove , update , returnNew , upsert , maxTime , maxTimeUnit , getWriteConcern ( ) ) ;


signature:
public class DBCollection { /** * 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 & gt ; = 2.6
 * @ param maxTimeUnit the unit that maxTime is specified in
 * @ param writeConcern the write concern to apply to this operation
 * @ 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 WriteConcernException if the write failed due some other failure specific to the update command
 * @ throws MongoException if the operation failed for some other reason
 * @ mongodb . driver . manual reference / command / findAndModify / Find and Modify
 * @ since 2.14.0 */
@ Nullable public DBObject findAndModify ( @ Nullable final DBObject query , @ Nullable final DBObject fields , @ Nullable final DBObject sort , final boolean remove , @ Nullable final DBObject update , final boolean returnNew , final boolean upsert , final long maxTime , final TimeUnit maxTimeUnit , final WriteConcern writeConcern ) { } }

implementation: return findAndModify ( query != null ? query : new BasicDBObject ( ) , new DBCollectionFindAndModifyOptions ( ) . projection ( fields ) . sort ( sort ) . remove ( remove ) . update ( update ) . returnNew ( returnNew ) . upsert ( upsert ) . maxTime ( maxTime , maxTimeUnit ) . writeConcern ( writeConcern ) ) ;


signature:
public class DBCollection { /** * 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 options the options regarding the find and modify operation
 * @ return the document as it was before the modifications , unless { @ code oprtions . returnNew } is true , in which case it returns the
 * document after the changes were made
 * @ throws WriteConcernException if the write failed due some other failure specific to the update command
 * @ throws MongoException if the operation failed for some other reason
 * @ mongodb . driver . manual reference / command / findAndModify / Find and Modify
 * @ since 3.4 */
public DBObject findAndModify ( final DBObject query , final DBCollectionFindAndModifyOptions options ) { } }

implementation: notNull ( "query" , query ) ; notNull ( "options" , options ) ; WriteConcern optionsWriteConcern = options . getWriteConcern ( ) ; WriteConcern writeConcern = optionsWriteConcern != null ? optionsWriteConcern : getWriteConcern ( ) ; WriteOperation < DBObject > operation ; if ( options . isRemove ( ) ) { operation = new FindAndDeleteOperation < DBObject > ( getNamespace ( ) , writeConcern , retryWrites , objectCodec ) . filter ( wrapAllowNull ( query ) ) . projection ( wrapAllowNull ( options . getProjection ( ) ) ) . sort ( wrapAllowNull ( options . getSort ( ) ) ) . maxTime ( options . getMaxTime ( MILLISECONDS ) , MILLISECONDS ) . collation ( options . getCollation ( ) ) ; } else { DBObject update = options . getUpdate ( ) ; if ( update == null ) { throw new IllegalArgumentException ( "update can not be null unless it's a remove" ) ; } if ( ! update . keySet ( ) . isEmpty ( ) && update . keySet ( ) . iterator ( ) . next ( ) . charAt ( 0 ) == '$' ) { operation = new FindAndUpdateOperation < DBObject > ( getNamespace ( ) , writeConcern , retryWrites , objectCodec , wrap ( update ) ) . filter ( wrap ( query ) ) . projection ( wrapAllowNull ( options . getProjection ( ) ) ) . sort ( wrapAllowNull ( options . getSort ( ) ) ) . returnOriginal ( ! options . returnNew ( ) ) . upsert ( options . isUpsert ( ) ) . maxTime ( options . getMaxTime ( MILLISECONDS ) , MILLISECONDS ) . bypassDocumentValidation ( options . getBypassDocumentValidation ( ) ) . collation ( options . getCollation ( ) ) . arrayFilters ( wrapAllowNull ( options . getArrayFilters ( ) , ( Encoder < DBObject > ) null ) ) ; } else { operation = new FindAndReplaceOperation < DBObject > ( getNamespace ( ) , writeConcern , retryWrites , objectCodec , wrap ( update ) ) . filter ( wrap ( query ) ) . projection ( wrapAllowNull ( options . getProjection ( ) ) ) . sort ( wrapAllowNull ( options . getSort ( ) ) ) . returnOriginal ( ! options . returnNew ( ) ) . upsert ( options . isUpsert ( ) ) . maxTime ( options . getMaxTime ( MILLISECONDS ) , MILLISECONDS ) . bypassDocumentValidation ( options . getBypassDocumentValidation ( ) ) . collation ( options . getCollation ( ) ) ; } } try { return executor . execute ( operation , getReadConcern ( ) ) ; } catch ( MongoWriteConcernException e ) { throw createWriteConcernException ( e ) ; }


signature:
public class DBCollection { /** * Drops ( deletes ) this collection from the database . Use with care .
 * @ throws MongoException if the operation failed
 * @ mongodb . driver . manual reference / command / drop / Drop Command */
public void drop ( ) { } }

implementation: try { executor . execute ( new DropCollectionOperation ( getNamespace ( ) , getWriteConcern ( ) ) , getReadConcern ( ) ) ; } catch ( MongoWriteConcernException e ) { throw createWriteConcernException ( e ) ; }


signature:
public class DBCollection { /** * Set a custom decoder factory for this collection . Set to null to use the default from MongoOptions .
 * @ param factory the factory to set . */
public synchronized void setDBDecoderFactory ( @ Nullable final DBDecoderFactory factory ) { } }

implementation:
this . decoderFactory = factory ; // Are we are using default factory ?
// If yes then we can use CollectibleDBObjectCodec directly , otherwise it will be wrapped .
Decoder < DBObject > decoder = ( factory == null || factory == DefaultDBDecoder . FACTORY ) ? getDefaultDBObjectCodec ( ) : new DBDecoderAdapter ( factory . create ( ) , this , getBufferPool ( ) ) ; this . objectCodec = new CompoundDBObjectCodec ( objectCodec . getEncoder ( ) , decoder ) ;


signature:
public class DBCollection { /** * Set a custom encoder factory for this collection . Set to null to use the default from MongoOptions .
 * @ param factory the factory to set . */
public synchronized void setDBEncoderFactory ( @ Nullable final DBEncoderFactory factory ) { } }

implementation:
this . encoderFactory = factory ; // Are we are using default factory ?
// If yes then we can use CollectibleDBObjectCodec directly , otherwise it will be wrapped .
Encoder < DBObject > encoder = ( factory == null || factory == DefaultDBEncoder . FACTORY ) ? getDefaultDBObjectCodec ( ) : new DBEncoderFactoryAdapter ( encoderFactory ) ; this . objectCodec = new CompoundDBObjectCodec ( encoder , objectCodec . getDecoder ( ) ) ;


signature:
public class DBCollection { /** * Return a list of the indexes for this collection . Each object in the list is the " info document " from MongoDB
 * @ return list of index documents
 * @ throws MongoException if the operation failed
 * @ mongodb . driver . manual core / indexes / Indexes */
public List < DBObject > getIndexInfo ( ) { } }

implementation: return new MongoIterableImpl < DBObject > ( null , executor , ReadConcern . DEFAULT , primary ( ) , retryReads ) { @ Override public ReadOperation < BatchCursor < DBObject > > asReadOperation ( ) { return new ListIndexesOperation < DBObject > ( getNamespace ( ) , getDefaultDBObjectCodec ( ) ) . retryReads ( retryReads ) ; } } . into ( new ArrayList < DBObject > ( ) ) ;


signature:
public class DBCollection { /** * Drops an index from this collection . The DBObject index parameter must match the specification of the index to drop , i . e . correct
 * key name and type must be specified .
 * @ param index the specification of the index to drop
 * @ throws MongoException if the index does not exist
 * @ mongodb . driver . manual core / indexes / Indexes */
public void dropIndex ( final DBObject index ) { } }

implementation: try { executor . execute ( new DropIndexOperation ( getNamespace ( ) , wrap ( index ) , getWriteConcern ( ) ) , getReadConcern ( ) ) ; } catch ( MongoWriteConcernException e ) { throw createWriteConcernException ( e ) ; }


signature:
public class DBCollection { /** * Drops the index with the given name from this collection .
 * @ param indexName name of index to drop
 * @ throws MongoException if the index does not exist
 * @ mongodb . driver . manual core / indexes / Indexes */
public void dropIndex ( final String indexName ) { } }

implementation: try { executor . execute ( new DropIndexOperation ( getNamespace ( ) , indexName , getWriteConcern ( ) ) , getReadConcern ( ) ) ; } catch ( MongoWriteConcernException e ) { throw createWriteConcernException ( e ) ; }


signature:
public class DBCollection { /** * Checks whether this collection is capped
 * @ return true if this is a capped collection
 * @ mongodb . driver . manual / core / capped - collections / # check - if - a - collection - is - capped Capped Collections */
public boolean isCapped ( ) { } }

implementation: CommandResult commandResult = getStats ( ) ; Object cappedField = commandResult . get ( "capped" ) ; return cappedField != null && ( cappedField . equals ( 1 ) || cappedField . equals ( true ) ) ;


signature:
public class DBCollection { /** * Sets the internal class for the given path in the document hierarchy
 * @ param path the path to map the given Class to
 * @ param aClass the Class to map the given path to */
public void setInternalClass ( final String path , final Class < ? extends DBObject > aClass ) { } }

implementation: setObjectFactory ( objectFactory . update ( aClass , asList ( path . split ( "\\." ) ) ) ) ;


signature:
public class DBCollection { /** * Gets the internal class for the given path in the document hierarchy
 * @ param path the path to map the given Class to
 * @ return the class for a given path in the hierarchy */
protected Class < ? extends DBObject > getInternalClass ( final String path ) { } }

implementation: return objectFactory . getClassForPath ( asList ( path . split ( "\\." ) ) ) ;


signature:
public class AsyncStreamHelper { /** * Converts a { @ link ByteBuffer } into a { @ link AsyncInputStream }
 * @ param srcByteBuffer the data source
 * @ return the AsyncInputStream */
public static AsyncInputStream toAsyncInputStream ( final ByteBuffer srcByteBuffer ) { } }

implementation: notNull ( "srcByteBuffer" , srcByteBuffer ) ; return new AsyncInputStream ( ) { @ Override public void read ( final ByteBuffer dstByteBuffer , final SingleResultCallback < Integer > callback ) { transferDataFromByteBuffers ( srcByteBuffer , dstByteBuffer , callback ) ; } @ Override public void skip ( final long bytesToSkip , final SingleResultCallback < Long > callback ) { notNull ( "callback" , callback ) ; callback . onResult ( 0L , null ) ; } @ Override public void close ( final SingleResultCallback < Void > callback ) { callback . onResult ( null , null ) ; } } ;


signature:
public class AsyncStreamHelper { /** * Converts a { @ link ByteBuffer } into a { @ link AsyncOutputStream }
 * @ param dstByteBuffer the data destination
 * @ return the AsyncOutputStream */
public static AsyncOutputStream toAsyncOutputStream ( final ByteBuffer dstByteBuffer ) { } }

implementation: notNull ( "dstByteBuffer" , dstByteBuffer ) ; return new AsyncOutputStream ( ) { @ Override public void write ( final ByteBuffer srcByteBuffer , final SingleResultCallback < Integer > callback ) { transferDataFromByteBuffers ( srcByteBuffer , dstByteBuffer , callback ) ; } @ Override public void close ( final SingleResultCallback < Void > callback ) { callback . onResult ( null , null ) ; } } ;


signature:
public class AsyncStreamHelper { /** * Converts a { @ link InputStream } into a { @ link AsyncInputStream }
 * @ param inputStream the InputStream
 * @ return the AsyncInputStream */
public static AsyncInputStream toAsyncInputStream ( final InputStream inputStream ) { } }

implementation: notNull ( "inputStream" , inputStream ) ; return new AsyncInputStream ( ) { @ Override public void read ( final ByteBuffer dstByteBuffer , final SingleResultCallback < Integer > callback ) { notNull ( "dst" , dstByteBuffer ) ; notNull ( "callback" , callback ) ; if ( ! dstByteBuffer . hasRemaining ( ) ) { callback . onResult ( - 1 , null ) ; return ; } int maxAmount = dstByteBuffer . remaining ( ) ; byte [ ] bytes = new byte [ maxAmount ] ; int amountRead ; try { amountRead = inputStream . read ( bytes ) ; } catch ( Throwable t ) { callback . onResult ( null , new MongoGridFSException ( "Error reading from input stream" , t ) ) ; return ; } if ( amountRead > 0 ) { if ( amountRead < maxAmount ) { byte [ ] dataRead = new byte [ amountRead ] ; System . arraycopy ( bytes , 0 , dataRead , 0 , amountRead ) ; dstByteBuffer . put ( dataRead ) ; } else { dstByteBuffer . put ( bytes ) ; } } callback . onResult ( amountRead , null ) ; } @ Override public void skip ( final long bytesToSkip , final SingleResultCallback < Long > callback ) { notNull ( "callback" , callback ) ; try { long skipped = inputStream . skip ( bytesToSkip ) ; callback . onResult ( skipped , null ) ; } catch ( Throwable t ) { callback . onResult ( null , t ) ; } } @ Override public void close ( final SingleResultCallback < Void > callback ) { try { inputStream . close ( ) ; } catch ( Throwable t ) { callback . onResult ( null , new MongoGridFSException ( "Error closing input stream" , t ) ) ; return ; } callback . onResult ( null , null ) ; } } ;


signature:
public class AsyncStreamHelper { /** * Converts a { @ link OutputStream } into a { @ link AsyncOutputStream }
 * @ param outputStream the OutputStream
 * @ return the AsyncOutputStream */
public static AsyncOutputStream toAsyncOutputStream ( final OutputStream outputStream ) { } }

implementation: notNull ( "outputStream" , outputStream ) ; return new AsyncOutputStream ( ) { @ Override public void write ( final ByteBuffer srcByteBuffer , final SingleResultCallback < Integer > callback ) { notNull ( "src" , srcByteBuffer ) ; notNull ( "callback" , callback ) ; if ( ! srcByteBuffer . hasRemaining ( ) ) { callback . onResult ( - 1 , null ) ; return ; } int amount = srcByteBuffer . remaining ( ) ; byte [ ] bytes = new byte [ amount ] ; try { srcByteBuffer . get ( bytes ) ; outputStream . write ( bytes ) ; } catch ( Throwable t ) { callback . onResult ( null , new MongoGridFSException ( "Error reading from input stream" , t ) ) ; return ; } callback . onResult ( amount , null ) ; } @ Override public void close ( final SingleResultCallback < Void > callback ) { try { outputStream . close ( ) ; } catch ( Throwable t ) { callback . onResult ( null , new MongoGridFSException ( "Error closing from output stream" , t ) ) ; return ; } callback . onResult ( null , null ) ; } } ;


signature:
public class PojoQuickTour { /** * Run this main method to see the output of this quick example .
 * @ param args takes an optional single argument for the connection string
 * @ throws InterruptedException if a latch is interrupted */
public static void main ( final String [ ] args ) throws InterruptedException { } }

implementation:
MongoClient mongoClient ; if ( args . length == 0 ) { // connect to the local database server
mongoClient = MongoClients . create ( ) ; } else { mongoClient = MongoClients . create ( args [ 0 ] ) ; } // create codec registry for POJOs
CodecRegistry pojoCodecRegistry = fromRegistries ( MongoClients . getDefaultCodecRegistry ( ) , fromProviders ( PojoCodecProvider . builder ( ) . automatic ( true ) . build ( ) ) ) ; // get handle to " mydb " database
MongoDatabase database = mongoClient . getDatabase ( "mydb" ) . withCodecRegistry ( pojoCodecRegistry ) ; // get a handle to the " people " collection
final MongoCollection < Person > collection = database . getCollection ( "people" , Person . class ) ; // drop all the data in it
final CountDownLatch dropLatch = new CountDownLatch ( 1 ) ; collection . drop ( new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { dropLatch . countDown ( ) ; } } ) ; dropLatch . await ( ) ; // make a document and insert it
final Person ada = new Person ( "Ada Byron" , 20 , new Address ( "St James Square" , "London" , "W1" ) ) ; System . out . println ( "Original Person Model: " + ada ) ; collection . insertOne ( ada , new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { // Person will now have an ObjectId
System . out . println ( "Mutated Person Model: " + ada ) ; System . out . println ( "Inserted!" ) ; } } ) ; // get it ( since it ' s the only one in there since we dropped the rest earlier on )
SingleResultCallback < Person > printCallback = new SingleResultCallback < Person > ( ) { @ Override public void onResult ( final Person person , final Throwable t ) { System . out . println ( person ) ; } } ; collection . find ( ) . first ( printCallback ) ; // now , lets add some more people so we can explore queries and cursors
List < Person > people = asList ( new Person ( "Charles Babbage" , 45 , new Address ( "5 Devonshire Street" , "London" , "W11" ) ) , new Person ( "Alan Turing" , 28 , new Address ( "Bletchley Hall" , "Bletchley Park" , "MK12" ) ) , new Person ( "Timothy Berners-Lee" , 61 , new Address ( "Colehill" , "Wimborne" , null ) ) ) ; final CountDownLatch countLatch = new CountDownLatch ( 1 ) ; collection . insertMany ( people , new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { collection . countDocuments ( new SingleResultCallback < Long > ( ) { @ Override public void onResult ( final Long count , final Throwable t ) { System . out . println ( "total # of people " + count ) ; countLatch . countDown ( ) ; } } ) ; } } ) ; countLatch . await ( ) ; System . out . println ( "" ) ; // lets get all the documents in the collection and print them out
Block < Person > printBlock = new Block < Person > ( ) { @ Override public void apply ( final Person person ) { System . out . println ( person ) ; } } ; SingleResultCallback < Void > callbackWhenFinished = new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { System . out . println ( "Operation Finished!" ) ; } } ; collection . find ( ) . forEach ( printBlock , callbackWhenFinished ) ; System . out . println ( "" ) ; // now use a query to get 1 document out
collection . find ( eq ( "address.city" , "Wimborne" ) ) . first ( printCallback ) ; System . out . println ( "" ) ; // now lets find every over 30
collection . find ( gt ( "age" , 30 ) ) . forEach ( printBlock , callbackWhenFinished ) ; System . out . println ( "" ) ; // Update One
SingleResultCallback < UpdateResult > printModifiedCount = new SingleResultCallback < UpdateResult > ( ) { @ Override public void onResult ( final UpdateResult result , final Throwable t ) { System . out . println ( result . getModifiedCount ( ) ) ; } } ; collection . updateOne ( eq ( "name" , "Ada Byron" ) , combine ( set ( "age" , 23 ) , set ( "name" , "Ada Lovelace" ) ) , printModifiedCount ) ; System . out . println ( "" ) ; // Update Many
collection . updateMany ( not ( eq ( "zip" , null ) ) , set ( "zip" , null ) , printModifiedCount ) ; System . out . println ( "" ) ; // Replace One
collection . replaceOne ( eq ( "name" , "Ada Lovelace" ) , ada , printModifiedCount ) ; // Delete One
SingleResultCallback < DeleteResult > printDeletedCount = new SingleResultCallback < DeleteResult > ( ) { @ Override public void onResult ( final DeleteResult result , final Throwable t ) { System . out . println ( result . getDeletedCount ( ) ) ; } } ; collection . deleteOne ( eq ( "address.city" , "Wimborne" ) , printDeletedCount ) ; // Delete Many
collection . deleteMany ( eq ( "address.city" , "London" ) , printDeletedCount ) ; // Clean up
final CountDownLatch deleteLatch = new CountDownLatch ( 1 ) ; database . drop ( new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { deleteLatch . countDown ( ) ; } } ) ; deleteLatch . await ( ) ; // release resources
mongoClient . close ( ) ;


signature:
public class Updates { /** * Creates an update that sets the value of the field with the given name to the given value .
 * @ param fieldName the non - null field name
 * @ param value the value , which may be null
 * @ param < TItem > the value type
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / set / $ set */
public static < TItem > Bson set ( final String fieldName , @ Nullable final TItem value ) { } }

implementation: return new SimpleUpdate < TItem > ( fieldName , value , "$set" ) ;


signature:
public class Updates { /** * Creates an update that sets the value of the field with the given name to the given value , but only if the update is an upsert that
 * results in an insert of a document .
 * @ param fieldName the non - null field name
 * @ param value the value , which may be null
 * @ param < TItem > the value type
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / setOnInsert / $ setOnInsert
 * @ see UpdateOptions # upsert ( boolean ) */
public static < TItem > Bson setOnInsert ( final String fieldName , @ Nullable final TItem value ) { } }

implementation: return new SimpleUpdate < TItem > ( fieldName , value , "$setOnInsert" ) ;


signature:
public class Updates { /** * Creates an update that renames a field .
 * @ param fieldName the non - null field name
 * @ param newFieldName the non - null new field name
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / rename / $ rename */
public static Bson rename ( final String fieldName , final String newFieldName ) { } }

implementation: notNull ( "newFieldName" , newFieldName ) ; return new SimpleUpdate < String > ( fieldName , newFieldName , "$rename" ) ;


signature:
public class Updates { /** * Creates an update that increments the value of the field with the given name by the given value .
 * @ param fieldName the non - null field name
 * @ param number the value
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / inc / $ inc */
public static Bson inc ( final String fieldName , final Number number ) { } }

implementation: notNull ( "number" , number ) ; return new SimpleUpdate < Number > ( fieldName , number , "$inc" ) ;


signature:
public class Updates { /** * Creates an update that multiplies the value of the field with the given name by the given number .
 * @ param fieldName the non - null field name
 * @ param number the non - null number
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / mul / $ mul */
public static Bson mul ( final String fieldName , final Number number ) { } }

implementation: notNull ( "number" , number ) ; return new SimpleUpdate < Number > ( fieldName , number , "$mul" ) ;


signature:
public class Updates { /** * Creates an update that sets the value of the field to the given value if the given value is less than the current value of the
 * field .
 * @ param fieldName the non - null field name
 * @ param value the value
 * @ param < TItem > the value type
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / min / $ min */
public static < TItem > Bson min ( final String fieldName , final TItem value ) { } }

implementation: return new SimpleUpdate < TItem > ( fieldName , value , "$min" ) ;


signature:
public class Updates { /** * Creates an update that sets the value of the field to the given value if the given value is greater than the current value of the
 * field .
 * @ param fieldName the non - null field name
 * @ param value the value
 * @ param < TItem > the value type
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / min / $ min */
public static < TItem > Bson max ( final String fieldName , final TItem value ) { } }

implementation: return new SimpleUpdate < TItem > ( fieldName , value , "$max" ) ;


signature:
public class Updates { /** * Creates an update that adds the given value to the array value of the field with the given name , unless the value is
 * already present , in which case it does nothing
 * @ param fieldName the non - null field name
 * @ param value the value , which may be null
 * @ param < TItem > the value type
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / addToSet / $ addToSet */
public static < TItem > Bson addToSet ( final String fieldName , @ Nullable final TItem value ) { } }

implementation: return new SimpleUpdate < TItem > ( fieldName , value , "$addToSet" ) ;


signature:
public class Updates { /** * Creates an update that adds each of the given values to the array value of the field with the given name , unless the value is
 * already present , in which case it does nothing
 * @ param fieldName the non - null field name
 * @ param values the values
 * @ param < TItem > the value type
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / addToSet / $ addToSet */
public static < TItem > Bson addEachToSet ( final String fieldName , final List < TItem > values ) { } }

implementation: return new WithEachUpdate < TItem > ( fieldName , values , "$addToSet" ) ;


signature:
public class Updates { /** * Creates an update that adds the given value to the array value of the field with the given name .
 * @ param fieldName the non - null field name
 * @ param value the value , which may be null
 * @ param < TItem > the value type
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / push / $ push */
public static < TItem > Bson push ( final String fieldName , @ Nullable final TItem value ) { } }

implementation: return new SimpleUpdate < TItem > ( fieldName , value , "$push" ) ;


signature:
public class Updates { /** * Creates an update that adds each of the given values to the array value of the field with the given name .
 * @ param fieldName the non - null field name
 * @ param values the values
 * @ param < TItem > the value type
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / push / $ push */
public static < TItem > Bson pushEach ( final String fieldName , final List < TItem > values ) { } }

implementation: return new PushUpdate < TItem > ( fieldName , values , new PushOptions ( ) ) ;


signature:
public class Updates { /** * Creates an update that removes all instances of the given value from the array value of the field with the given name .
 * @ param fieldName the non - null field name
 * @ param value the value , which may be null
 * @ param < TItem > the value type
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / pull / $ pull */
public static < TItem > Bson pull ( final String fieldName , @ Nullable final TItem value ) { } }

implementation: return new SimpleUpdate < TItem > ( fieldName , value , "$pull" ) ;


signature:
public class Updates { /** * Creates an update that removes from an array all elements that match the given filter .
 * @ param filter the query filter
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / pull / $ pull */
public static Bson pullByFilter ( final Bson filter ) { } }

implementation: return new Bson ( ) { @ Override public < TDocument > BsonDocument toBsonDocument ( final Class < TDocument > tDocumentClass , final CodecRegistry codecRegistry ) { BsonDocumentWriter writer = new BsonDocumentWriter ( new BsonDocument ( ) ) ; writer . writeStartDocument ( ) ; writer . writeName ( "$pull" ) ; encodeValue ( writer , filter , codecRegistry ) ; writer . writeEndDocument ( ) ; return writer . getDocument ( ) ; } } ;


signature:
public class Updates { /** * Creates an update that removes all instances of the given values from the array value of the field with the given name .
 * @ param fieldName the non - null field name
 * @ param values the values
 * @ param < TItem > the value type
 * @ return the update
 * @ mongodb . driver . manual reference / operator / update / pull / $ pull */
public static < TItem > Bson pullAll ( final String fieldName , final List < TItem > values ) { } }

implementation: return new PullAllUpdate < TItem > ( fieldName , values ) ;


signature:
public class BaseQueryMessage { /** * Write the query prologue to the given BSON output .
 * @ param bsonOutput the BSON output */
protected void writeQueryPrologue ( final BsonOutput bsonOutput ) { } }

implementation: bsonOutput . writeInt32 ( getCursorFlag ( ) ) ; bsonOutput . writeCString ( getCollectionName ( ) ) ; bsonOutput . writeInt32 ( skip ) ; bsonOutput . writeInt32 ( numberToReturn ) ;


signature:
public class MongoNamespace { /** * Check the validity of the given database name . A valid database name is non - null , non - empty , and does not contain any of the
 * following characters : { @ code ' \ 0 ' , ' / ' , ' \ \ ' , ' ' , ' " ' , ' . ' } . The server may impose additional restrictions on database names .
 * @ param databaseName the database name
 * @ throws IllegalArgumentException if the database name is invalid
 * @ since 3.4
 * @ mongodb . driver . manual reference / limits / # naming - restrictions Naming Restrictions */
public static void checkDatabaseNameValidity ( final String databaseName ) { } }

implementation: notNull ( "databaseName" , databaseName ) ; isTrueArgument ( "databaseName is not empty" , ! databaseName . isEmpty ( ) ) ; for ( int i = 0 ; i < databaseName . length ( ) ; i ++ ) { isTrueArgument ( "databaseName does not contain '" + databaseName . charAt ( i ) + "'" , ! PROHIBITED_CHARACTERS_IN_DATABASE_NAME . contains ( databaseName . charAt ( i ) ) ) ; }


signature:
public class DefaultConnectionPool { /** * If there was a socket exception that wasn ' t some form of interrupted read , increment the generation count so that any connections
 * created prior will be discarded .
 * @ param connection the connection that generated the exception
 * @ param t the exception */
private void incrementGenerationOnSocketException ( final InternalConnection connection , final Throwable t ) { } }

implementation: if ( t instanceof MongoSocketException && ! ( t instanceof MongoSocketReadTimeoutException ) ) { if ( LOGGER . isWarnEnabled ( ) ) { LOGGER . warn ( format ( "Got socket exception on connection [%s] to %s. All connections to %s will be closed." , getId ( connection ) , serverId . getAddress ( ) , serverId . getAddress ( ) ) ) ; } invalidate ( ) ; }


signature:
public class Decimal128LegacyAPIQuickTour { /** * Run this main method to see the output of this quick example .
 * @ param args takes an optional single argument for the connection string */
public static void main ( final String [ ] args ) { } }

implementation:
MongoClient mongoClient ; if ( args . length == 0 ) { // connect to the local database server
mongoClient = new MongoClient ( ) ; } else { mongoClient = new MongoClient ( new MongoClientURI ( args [ 0 ] ) ) ; } // get handle to " mydb " database
DB database = mongoClient . getDB ( "mydb" ) ; // get a handle to the " test " collection
DBCollection collection = database . getCollection ( "test" ) ; // drop all the data in it
collection . drop ( ) ; // make a document and insert it
BasicDBObject doc = new BasicDBObject ( "name" , "MongoDB" ) . append ( "amount1" , Decimal128 . parse ( ".10" ) ) . append ( "amount2" , new Decimal128 ( 42L ) ) . append ( "amount3" , new Decimal128 ( new BigDecimal ( ".200" ) ) ) ; collection . insert ( doc ) ; DBObject first = collection . findOne ( QueryBuilder . start ( "amount1" ) . is ( new Decimal128 ( new BigDecimal ( ".10" ) ) ) . get ( ) ) ; Decimal128 amount3 = ( Decimal128 ) first . get ( "amount3" ) ; BigDecimal amount2AsBigDecimal = amount3 . bigDecimalValue ( ) ; System . out . println ( amount3 . toString ( ) ) ; System . out . println ( amount2AsBigDecimal . toString ( ) ) ;


signature:
public class FindAndUpdateOperation { /** * Sets the maximum execution time on the server for this operation .
 * @ param maxTime the max time
 * @ param timeUnit the time unit , which may not be null
 * @ return this */
public FindAndUpdateOperation < T > maxTime ( final long maxTime , final TimeUnit timeUnit ) { } }

implementation: notNull ( "timeUnit" , timeUnit ) ; this . maxTimeMS = MILLISECONDS . convert ( maxTime , timeUnit ) ; return this ;


signature:
public class ClassMap { /** * Helper method that walks superclass and interface graph , superclasses first , then interfaces , to compute an ancestry list . Super
 * types are visited left to right . Duplicates are removed such that no Class will appear in the list before one of its subtypes .
 * @ param clazz the class to get the ancestors for
 * @ param < T > the type of the class modeled by this { @ code Class } object .
 * @ return a list of all the super classes of { @ code clazz } , starting with the class , and ending with { @ code java . lang . Object } . */
public static < T > List < Class < ? > > getAncestry ( final Class < T > clazz ) { } }

implementation: return ClassAncestry . getAncestry ( clazz ) ;


signature:
public class ClassMap { /** * As per { @ code java . util . Map } , associates the specified value with the specified key in this map . If the map previously contained a
 * mapping for the key , the old value is replaced by the specified value .
 * @ param key a { @ code Class } key
 * @ param value the value for this class
 * @ return the previous value associated with { @ code key } , or null if there was no mapping for key .
 * @ see java . util . Map # put ( Object , Object ) */
public T put ( final Class < ? > key , final T value ) { } }

implementation: try { return map . put ( key , value ) ; } finally { cache . clear ( ) ; }


signature:
public class Projections { /** * Creates a projection of a field whose value is computed from the given expression . Projection with an expression is only supported
 * using the $ project aggregation pipeline stage .
 * @ param fieldName the field name
 * @ param expression the expression
 * @ param < TExpression > the expression type
 * @ return the projection
 * @ see Aggregates # project ( Bson ) */
public static < TExpression > Bson computed ( final String fieldName , final TExpression expression ) { } }

implementation: return new SimpleExpression < TExpression > ( fieldName , expression ) ;


signature:
public class Projections { /** * Creates a projection to the given field name of a slice of the array value of that field .
 * @ param fieldName the field name
 * @ param limit the number of elements to project .
 * @ return the projection
 * @ mongodb . driver . manual reference / operator / projection / slice Slice */
public static Bson slice ( final String fieldName , final int limit ) { } }

implementation: return new BsonDocument ( fieldName , new BsonDocument ( "$slice" , new BsonInt32 ( limit ) ) ) ;


signature:
public class Projections { /** * Creates a projection to the given field name of a slice of the array value of that field .
 * @ param fieldName the field name
 * @ param skip the number of elements to skip before applying the limit
 * @ param limit the number of elements to project
 * @ return the projection
 * @ mongodb . driver . manual reference / operator / projection / slice Slice */
public static Bson slice ( final String fieldName , final int skip , final int limit ) { } }

implementation: return new BsonDocument ( fieldName , new BsonDocument ( "$slice" , new BsonArray ( asList ( new BsonInt32 ( skip ) , new BsonInt32 ( limit ) ) ) ) ) ;


signature:
public class DefaultDnsResolver { /** * The format of SRV record is
 * priority weight port target .
 * e . g .
 * 0 5 5060 example . com .
 * The priority and weight are ignored , and we just concatenate the host ( after removing the ending ' . ' ) and port with a
 * ' : ' in between , as expected by ServerAddress .
 * It ' s required that the srvHost has at least three parts ( e . g . foo . bar . baz ) and that all of the resolved hosts have a parent
 * domain equal to the domain of the srvHost . */
@ Override public List < String > resolveHostFromSrvRecords ( final String srvHost ) { } }

implementation:
String srvHostDomain = srvHost . substring ( srvHost . indexOf ( '.' ) + 1 ) ; List < String > srvHostDomainParts = asList ( srvHostDomain . split ( "\\." ) ) ; List < String > hosts = new ArrayList < String > ( ) ; InitialDirContext dirContext = createDnsDirContext ( ) ; try { Attributes attributes = dirContext . getAttributes ( "_mongodb._tcp." + srvHost , new String [ ] { "SRV" } ) ; Attribute attribute = attributes . get ( "SRV" ) ; if ( attribute == null ) { throw new MongoConfigurationException ( "No SRV records available for host " + srvHost ) ; } NamingEnumeration < ? > srvRecordEnumeration = attribute . getAll ( ) ; while ( srvRecordEnumeration . hasMore ( ) ) { String srvRecord = ( String ) srvRecordEnumeration . next ( ) ; String [ ] split = srvRecord . split ( " " ) ; String resolvedHost = split [ 3 ] . endsWith ( "." ) ? split [ 3 ] . substring ( 0 , split [ 3 ] . length ( ) - 1 ) : split [ 3 ] ; String resolvedHostDomain = resolvedHost . substring ( resolvedHost . indexOf ( '.' ) + 1 ) ; if ( ! sameParentDomain ( srvHostDomainParts , resolvedHostDomain ) ) { throw new MongoConfigurationException ( format ( "The SRV host name '%s'resolved to a host '%s 'that is not in a sub-domain of the SRV host." , srvHost , resolvedHost ) ) ; } hosts . add ( resolvedHost + ":" + split [ 2 ] ) ; } if ( hosts . isEmpty ( ) ) { throw new MongoConfigurationException ( "Unable to find any SRV records for host " + srvHost ) ; } } catch ( NamingException e ) { throw new MongoConfigurationException ( "Unable to look up SRV record for host " + srvHost , e ) ; } finally { try { dirContext . close ( ) ; } catch ( NamingException e ) { // ignore
} } return hosts ;


signature:
public class DefaultDnsResolver { /** * A TXT record is just a string
 * We require each to be one or more query parameters for a MongoDB connection string .
 * Here we concatenate TXT records together with a ' & ' separator as required by connection strings */
@ Override public String resolveAdditionalQueryParametersFromTxtRecords ( final String host ) { } }

implementation:
String additionalQueryParameters = "" ; InitialDirContext dirContext = createDnsDirContext ( ) ; try { Attributes attributes = dirContext . getAttributes ( host , new String [ ] { "TXT" } ) ; Attribute attribute = attributes . get ( "TXT" ) ; if ( attribute != null ) { NamingEnumeration < ? > txtRecordEnumeration = attribute . getAll ( ) ; if ( txtRecordEnumeration . hasMore ( ) ) { // Remove all space characters , as the DNS resolver for TXT records inserts a space character
// between each character - string in a single TXT record . That whitespace is spurious in
// this context and must be removed
additionalQueryParameters = ( ( String ) txtRecordEnumeration . next ( ) ) . replaceAll ( "\\s" , "" ) ; if ( txtRecordEnumeration . hasMore ( ) ) { throw new MongoConfigurationException ( format ( "Multiple TXT records found for host '%s'.  Only one is permitted" , host ) ) ; } } } } catch ( NamingException e ) { throw new MongoConfigurationException ( "Unable to look up TXT record for host " + host , e ) ; } finally { try { dirContext . close ( ) ; } catch ( NamingException e ) { // ignore
} } return additionalQueryParameters ;


signature:
public class DefaultDnsResolver { /** * It ' s unfortunate that we take a runtime dependency on com . sun . jndi . dns . DnsContextFactory .
 * This is not guaranteed to work on all JVMs but in practice is expected to work on most . */
private static InitialDirContext createDnsDirContext ( ) { } }

implementation: Hashtable < String , String > envProps = new Hashtable < String , String > ( ) ; envProps . put ( Context . INITIAL_CONTEXT_FACTORY , "com.sun.jndi.dns.DnsContextFactory" ) ; try { return new InitialDirContext ( envProps ) ; } catch ( NamingException e ) { throw new MongoClientException ( "Unable to support mongodb+srv// style connections as the 'com.sun.jndi.dns.DnsContextFactory' " + "class is not available in this JRE. A JNDI context is required for resolving SRV records." , e ) ; }


signature:
public class DBCollectionCountOptions { /** * Sets the maximum execution time on the server for this operation .
 * @ param maxTime the max time
 * @ param timeUnit the time unit , which may not be null
 * @ return this */
public DBCollectionCountOptions maxTime ( final long maxTime , final TimeUnit timeUnit ) { } }

implementation: notNull ( "timeUnit" , timeUnit ) ; this . maxTimeMS = TimeUnit . MILLISECONDS . convert ( maxTime , timeUnit ) ; return this ;


signature:
public class ReplaceOptions { /** * Creates replace options from updateOptions .
 * @ param updateOptions the updateOptions
 * @ return replace options
 * @ deprecated there is no replacement for this method */
@ Deprecated public static ReplaceOptions createReplaceOptions ( final UpdateOptions updateOptions ) { } }

implementation: notNull ( "updateOptions" , updateOptions ) ; List < ? extends Bson > arrayFilters = updateOptions . getArrayFilters ( ) ; isTrue ( "ArrayFilters should be empty." , arrayFilters == null || arrayFilters . isEmpty ( ) ) ; return new ReplaceOptions ( ) . bypassDocumentValidation ( updateOptions . getBypassDocumentValidation ( ) ) . collation ( updateOptions . getCollation ( ) ) . upsert ( updateOptions . isUpsert ( ) ) ;


signature:
public class Base64 { /** * Decodes the given Base64 - encoded string .
 * @ param s the Base64 - encoded string
 * @ return the decoded byte array */
public static byte [ ] decode ( final String s ) { } }

implementation: int delta = s . endsWith ( "==" ) ? 2 : s . endsWith ( "=" ) ? 1 : 0 ; byte [ ] buffer = new byte [ s . length ( ) * BYTES_PER_UNENCODED_BLOCK / BYTES_PER_ENCODED_BLOCK - delta ] ; int mask = 0xFF ; int pos = 0 ; for ( int i = 0 ; i < s . length ( ) ; i += BYTES_PER_ENCODED_BLOCK ) { int c0 = DECODE_TABLE [ s . charAt ( i ) ] ; int c1 = DECODE_TABLE [ s . charAt ( i + 1 ) ] ; buffer [ pos ++ ] = ( byte ) ( ( ( c0 << 2 ) | ( c1 >> 4 ) ) & mask ) ; if ( pos >= buffer . length ) { return buffer ; } int c2 = DECODE_TABLE [ s . charAt ( i + 2 ) ] ; buffer [ pos ++ ] = ( byte ) ( ( ( c1 << 4 ) | ( c2 >> 2 ) ) & mask ) ; if ( pos >= buffer . length ) { return buffer ; } int c3 = DECODE_TABLE [ s . charAt ( i + 3 ) ] ; buffer [ pos ++ ] = ( byte ) ( ( ( c2 << 6 ) | c3 ) & mask ) ; } return buffer ;


signature:
public class Base64 { /** * Encodes the given byte array into a Base64 - encoded string .
 * @ param in the byte array
 * @ return the Base64 - encoded string */
public static String encode ( final byte [ ] in ) { } }

implementation:
int modulus = 0 ; int bitWorkArea = 0 ; int numEncodedBytes = ( in . length / BYTES_PER_UNENCODED_BLOCK ) * BYTES_PER_ENCODED_BLOCK + ( ( in . length % BYTES_PER_UNENCODED_BLOCK == 0 ) ? 0 : 4 ) ; byte [ ] buffer = new byte [ numEncodedBytes ] ; int pos = 0 ; for ( int b : in ) { modulus = ( modulus + 1 ) % BYTES_PER_UNENCODED_BLOCK ; if ( b < 0 ) { b += 256 ; } bitWorkArea = ( bitWorkArea << 8 ) + b ; // BITS _ PER _ BYTE
if ( 0 == modulus ) { // 3 bytes = 24 bits = 4 * 6 bits to extract
buffer [ pos ++ ] = ENCODE_TABLE [ ( bitWorkArea >> 18 ) & SIX_BIT_MASK ] ; buffer [ pos ++ ] = ENCODE_TABLE [ ( bitWorkArea >> 12 ) & SIX_BIT_MASK ] ; buffer [ pos ++ ] = ENCODE_TABLE [ ( bitWorkArea >> 6 ) & SIX_BIT_MASK ] ; buffer [ pos ++ ] = ENCODE_TABLE [ bitWorkArea & SIX_BIT_MASK ] ; } } switch ( modulus ) { // 0-2
case 1 : // 8 bits = 6 + 2
buffer [ pos ++ ] = ENCODE_TABLE [ ( bitWorkArea >> 2 ) & SIX_BIT_MASK ] ; // top 6 bits
buffer [ pos ++ ] = ENCODE_TABLE [ ( bitWorkArea << 4 ) & SIX_BIT_MASK ] ; // remaining 2
buffer [ pos ++ ] = PAD ; buffer [ pos ] = PAD ; // Last entry no need to + +
break ; case 2 : // 16 bits = 6 + 6 + 4
buffer [ pos ++ ] = ENCODE_TABLE [ ( bitWorkArea >> 10 ) & SIX_BIT_MASK ] ; buffer [ pos ++ ] = ENCODE_TABLE [ ( bitWorkArea >> 4 ) & SIX_BIT_MASK ] ; buffer [ pos ++ ] = ENCODE_TABLE [ ( bitWorkArea << 2 ) & SIX_BIT_MASK ] ; buffer [ pos ] = PAD ; // Last entry no need to + +
break ; default : break ; } return byteArrayToString ( buffer ) ;


signature:
public class Mongo { /** * Gets the address of the current master
 * @ return the address */
@ Deprecated @ SuppressWarnings ( "deprecation" ) @ Nullable public ServerAddress getAddress ( ) { } }

implementation: ClusterDescription description = getClusterDescription ( ) ; if ( description . getPrimaries ( ) . isEmpty ( ) ) { return null ; } return description . getPrimaries ( ) . get ( 0 ) . getAddress ( ) ;


signature:
public class Mongo { /** * Get the status of the replica set cluster .
 * @ return replica set status information */
@ SuppressWarnings ( "deprecation" ) @ Deprecated @ Nullable public ReplicaSetStatus getReplicaSetStatus ( ) { } }

implementation: ClusterDescription clusterDescription = getClusterDescription ( ) ; return clusterDescription . getType ( ) == REPLICA_SET && clusterDescription . getConnectionMode ( ) == MULTIPLE ? new ReplicaSetStatus ( delegate . getCluster ( ) ) : null ; // this is intended behavior in 2 . x


signature:
public class Mongo { /** * Gets a list of the names of all databases on the connected server .
 * @ return list of database names
 * @ throws MongoException if the operation fails
 * @ deprecated Replaced with { @ link com . mongodb . MongoClient # listDatabaseNames ( ) } */
@ Deprecated public List < String > getDatabaseNames ( ) { } }

implementation: return new MongoIterableImpl < DBObject > ( null , createOperationExecutor ( ) , ReadConcern . DEFAULT , primary ( ) , options . getRetryReads ( ) ) { @ Override public ReadOperation < BatchCursor < DBObject > > asReadOperation ( ) { return new ListDatabasesOperation < DBObject > ( MongoClient . getCommandCodec ( ) ) ; } } . map ( new Function < DBObject , String > ( ) { @ Override public String apply ( final DBObject result ) { return ( String ) result . get ( "name" ) ; } } ) . into ( new ArrayList < String > ( ) ) ;


signature:
public class Mongo { /** * Gets a database object . Users should use { @ link com . mongodb . MongoClient # getDatabase ( String ) } instead .
 * The { @ link DB } class has been superseded by { @ link com . mongodb . client . MongoDatabase } . The deprecation of this method effectively
 * deprecates the { @ link DB } , { @ link DBCollection } , and { @ link DBCursor } classes , among others ; but in order to give users time to
 * migrate to the new API without experiencing a huge number of compiler warnings , those classes have not yet been formally
 * deprecated .
 * @ param dbName the name of the database to retrieve
 * @ return a DB representing the specified database
 * @ throws IllegalArgumentException if the name is invalid
 * @ see MongoNamespace # checkDatabaseNameValidity ( String )
 * @ deprecated This method is not currently scheduled for removal , but prefer { @ link com . mongodb . MongoClient # getDatabase ( String ) } for
 * new code . Note that { @ link DB } and { @ link com . mongodb . client . MongoDatabase } can be used together in the same application , whith the
 * same { @ link MongoClient } instance . */
@ Deprecated // NOT CURRENTLY INTENDED FOR REMOVAL
public DB getDB ( final String dbName ) { } }

implementation: DB db = dbCache . get ( dbName ) ; if ( db != null ) { return db ; } db = new DB ( this , dbName , createOperationExecutor ( ) ) ; DB temp = dbCache . putIfAbsent ( dbName , db ) ; if ( temp != null ) { return temp ; } return db ;


signature:
public class Mongo { /** * Forces the master server to fsync the RAM data to disk This is done automatically by the server at intervals , but can be forced for
 * better reliability .
 * @ param async if true , the fsync will be done asynchronously on the server .
 * @ return result of the command execution
 * @ throws MongoException if there ' s a failure
 * @ mongodb . driver . manual reference / command / fsync / fsync command */
@ Deprecated public CommandResult fsync ( final boolean async ) { } }

implementation: DBObject command = new BasicDBObject ( "fsync" , 1 ) ; if ( async ) { command . put ( "async" , 1 ) ; } return getDB ( ADMIN_DATABASE_NAME ) . command ( command ) ;


signature:
public class Mongo { /** * Forces the master server to fsync the RAM data to disk , then lock all writes . The database will be read - only after this command
 * returns .
 * @ return result of the command execution
 * @ throws MongoException if there ' s a failure
 * @ mongodb . driver . manual reference / command / fsync / fsync command */
@ Deprecated public CommandResult fsyncAndLock ( ) { } }

implementation: DBObject command = new BasicDBObject ( "fsync" , 1 ) ; command . put ( "lock" , 1 ) ; return getDB ( ADMIN_DATABASE_NAME ) . command ( command ) ;


signature:
public class Mongo { /** * Unlocks the database , allowing the write operations to go through . This command may be asynchronous on the server , which means there
 * may be a small delay before the database becomes writable .
 * @ return { @ code DBObject } in the following form { @ code { " ok " : 1 , " info " : " unlock completed " } }
 * @ throws MongoException if there ' s a failure
 * @ mongodb . driver . manual reference / command / fsync / fsync command */
@ Deprecated public DBObject unlock ( ) { } }

implementation: return DBObjects . toDBObject ( createOperationExecutor ( ) . execute ( new FsyncUnlockOperation ( ) , readPreference , readConcern ) ) ;


signature:
public class Mongo { /** * Returns true if the database is locked ( read - only ) , false otherwise .
 * @ return result of the command execution
 * @ throws MongoException if the operation fails
 * @ mongodb . driver . manual reference / command / fsync / fsync command */
@ Deprecated public boolean isLocked ( ) { } }

implementation: return createOperationExecutor ( ) . execute ( new CurrentOpOperation ( ) , ReadPreference . primary ( ) , readConcern ) . getBoolean ( "fsyncLock" , BsonBoolean . FALSE ) . getValue ( ) ;


signature:
public class Mongo { /** * Gets a { @ code String } representation of current connection point , i . e . master .
 * @ return server address in a host : port form */
@ Deprecated @ Nullable public String getConnectPoint ( ) { } }

implementation: ServerAddress master = getAddress ( ) ; return master != null ? String . format ( "%s:%d" , master . getHost ( ) , master . getPort ( ) ) : null ;


signature:
public class ClientSessionImpl { /** * TODO : should there be a version of this that takes a callback ? */
@ Override public void close ( ) { } }

implementation: if ( transactionState == TransactionState . IN ) { abortTransaction ( new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { ClientSessionImpl . super . close ( ) ; } } ) ; } else { super . close ( ) ; }


signature:
public class BsonValue { /** * Gets this value as a BsonNumber if it is one , otherwise throws exception
 * @ return a BsonNumber
 * @ throws org . bson . BsonInvalidOperationException if this value is not of the expected type */
public BsonNumber asNumber ( ) { } }

implementation: if ( getBsonType ( ) != BsonType . INT32 && getBsonType ( ) != BsonType . INT64 && getBsonType ( ) != BsonType . DOUBLE ) { throw new BsonInvalidOperationException ( format ( "Value expected to be of a numerical BSON type is of unexpected type %s" , getBsonType ( ) ) ) ; } return ( BsonNumber ) this ;


signature:
public class ConnectionId { /** * Creates a new connectionId with the set server value
 * @ param serverValue the server value
 * @ return the new connection id
 * @ since 3.8 */
public ConnectionId withServerValue ( final int serverValue ) { } }

implementation: isTrue ( "server value is null" , this . serverValue == null ) ; return new ConnectionId ( serverId , localValue , serverValue ) ;


signature:
public class ClassAncestry { /** * < p > Walks superclass and interface graph , superclasses first , then interfaces , to compute an ancestry list . Supertypes are visited
 * left
 * to right . Duplicates are removed such that no Class will appear in the list before one of its subtypes . < / p >
 * < p > Does not need to be synchronized , races are harmless as the Class graph does not change at runtime . < / p > */
public static < T > List < Class < ? > > getAncestry ( final Class < T > c ) { } }

implementation: ConcurrentMap < Class < ? > , List < Class < ? > > > cache = getClassAncestryCache ( ) ; while ( true ) { List < Class < ? > > cachedResult = cache . get ( c ) ; if ( cachedResult != null ) { return cachedResult ; } cache . putIfAbsent ( c , computeAncestry ( c ) ) ; }


signature:
public class ClassAncestry { /** * Starting with children and going back to parents */
private static List < Class < ? > > computeAncestry ( final Class < ? > c ) { } }

implementation: List < Class < ? > > result = new ArrayList < Class < ? > > ( ) ; result . add ( Object . class ) ; computeAncestry ( c , result ) ; Collections . reverse ( result ) ; return unmodifiableList ( new ArrayList < Class < ? > > ( result ) ) ;


signature:
public class Geometry { /** * Converts to GeoJSON representation
 * @ return the GeoJSON representation */
@ SuppressWarnings ( { } }

implementation: "unchecked" , "rawtypes" , "deprecation" } ) public String toJson ( ) { StringWriter stringWriter = new StringWriter ( ) ; JsonWriter writer = new JsonWriter ( stringWriter , new JsonWriterSettings ( ) ) ; Codec codec = getRegistry ( ) . get ( getClass ( ) ) ; codec . encode ( writer , this , EncoderContext . builder ( ) . build ( ) ) ; return stringWriter . toString ( ) ;


signature:
public class MapReduceWithInlineResultsOperation { /** * Executing this will return a cursor with your results and the statistics in .
 * @ param binding the binding
 * @ return a MapReduceCursor that can be iterated over to find all the results of the Map Reduce operation . */
@ Override @ SuppressWarnings ( "unchecked" ) public MapReduceBatchCursor < T > execute ( final ReadBinding binding ) { } }

implementation: return executeCommand ( binding , namespace . getDatabaseName ( ) , getCommandCreator ( binding . getSessionContext ( ) ) , CommandResultDocumentCodec . create ( decoder , "results" ) , transformer ( ) , false ) ;


signature:
public class IndexOptions { /** * Gets the time to live for documents in the collection
 * @ return the time to live for documents in the collection
 * @ param timeUnit the time unit
 * @ mongodb . driver . manual tutorial / expire - data TTL */
@ Nullable public Long getExpireAfter ( final TimeUnit timeUnit ) { } }

implementation: if ( expireAfterSeconds == null ) { return null ; } return timeUnit . convert ( expireAfterSeconds , TimeUnit . SECONDS ) ;


signature:
public class IndexOptions { /** * Sets the time to live for documents in the collection
 * @ param expireAfter the time to live for documents in the collection
 * @ param timeUnit the time unit for expireAfter
 * @ return this
 * @ mongodb . driver . manual tutorial / expire - data TTL */
public IndexOptions expireAfter ( @ Nullable final Long expireAfter , final TimeUnit timeUnit ) { } }

implementation: if ( expireAfter == null ) { this . expireAfterSeconds = null ; } else { this . expireAfterSeconds = TimeUnit . SECONDS . convert ( expireAfter , timeUnit ) ; } return this ;


signature:
public class GroupCommand { /** * Turns this group command into the DBObject format of the command .
 * @ return a DBObject containing the group command as a MongoDB document */
public DBObject toDBObject ( ) { } }

implementation: DBObject args = new BasicDBObject ( "ns" , collectionName ) . append ( "cond" , condition ) . append ( "$reduce" , reduce ) . append ( "initial" , initial ) ; if ( keys != null ) { args . put ( "key" , keys ) ; } if ( keyf != null ) { args . put ( "$keyf" , keyf ) ; } if ( finalize != null ) { args . put ( "finalize" , finalize ) ; } return new BasicDBObject ( "group" , args ) ;


signature:
public class ClusterDescription { /** * Gets the logical session timeout in minutes , or null if at least one of the known servers does not support logical sessions .
 * @ return the logical session timeout in minutes , which may be null
 * @ mongodb . server . release 3.6
 * @ since 3.6 */
public Integer getLogicalSessionTimeoutMinutes ( ) { } }

implementation: Integer retVal = null ; for ( ServerDescription cur : getServersByPredicate ( new Predicate ( ) { @ Override public boolean apply ( final ServerDescription serverDescription ) { return serverDescription . isPrimary ( ) || serverDescription . isSecondary ( ) ; } } ) ) { if ( cur . getLogicalSessionTimeoutMinutes ( ) == null ) { return null ; } if ( retVal == null ) { retVal = cur . getLogicalSessionTimeoutMinutes ( ) ; } else { retVal = Math . min ( retVal , cur . getLogicalSessionTimeoutMinutes ( ) ) ; } } return retVal ;


signature:
public class ClusterDescription { /** * Returns the Set of all server descriptions in this cluster , sorted by the String value of the ServerAddress of each one .
 * @ return the set of server descriptions
 * @ deprecated Use { @ link # getServerDescriptions ( ) } instead */
@ Deprecated public Set < ServerDescription > getAll ( ) { } }

implementation: Set < ServerDescription > serverDescriptionSet = new TreeSet < ServerDescription > ( new Comparator < ServerDescription > ( ) { @ Override public int compare ( final ServerDescription o1 , final ServerDescription o2 ) { int val = o1 . getAddress ( ) . getHost ( ) . compareTo ( o2 . getAddress ( ) . getHost ( ) ) ; if ( val != 0 ) { return val ; } return integerCompare ( o1 . getAddress ( ) . getPort ( ) , o2 . getAddress ( ) . getPort ( ) ) ; } private int integerCompare ( final int p1 , final int p2 ) { return ( p1 < p2 ) ? - 1 : ( ( p1 == p2 ) ? 0 : 1 ) ; } } ) ; serverDescriptionSet . addAll ( serverDescriptions ) ; return Collections . unmodifiableSet ( serverDescriptionSet ) ;


signature:
public class ClusterDescription { /** * Returns the ServerDescription for the server at the given address
 * @ param serverAddress the ServerAddress for a server in this cluster
 * @ return the ServerDescription for this server
 * @ deprecated Replace with a filter on ServerDescription in the caller */
@ Deprecated public ServerDescription getByServerAddress ( final ServerAddress serverAddress ) { } }

implementation: for ( final ServerDescription cur : serverDescriptions ) { if ( cur . isOk ( ) && cur . getAddress ( ) . equals ( serverAddress ) ) { return cur ; } } return null ;


signature:
public class ClusterDescription { /** * While it may seem counter - intuitive that a MongoDB cluster can have more than one primary , it can in the case where the client ' s view
 * of the cluster is a set of mongos servers , any of which can serve as the primary .
 * @ return a list of servers that can act as primaries
 * @ deprecated Replace with a filter on ServerDescription in the caller */
@ Deprecated public List < ServerDescription > getPrimaries ( ) { } }

implementation: return getServersByPredicate ( new Predicate ( ) { public boolean apply ( final ServerDescription serverDescription ) { return serverDescription . isPrimary ( ) ; } } ) ;


signature:
public class ClusterDescription { /** * Get a list of all the secondaries in this cluster
 * @ return a List of ServerDescriptions of all the secondaries this cluster is currently aware of
 * @ deprecated Replace with a filter on ServerDescription in the caller */
@ Deprecated public List < ServerDescription > getSecondaries ( ) { } }

implementation: return getServersByPredicate ( new Predicate ( ) { public boolean apply ( final ServerDescription serverDescription ) { return serverDescription . isSecondary ( ) ; } } ) ;


signature:
public class ClusterDescription { /** * Get a list of all the secondaries in this cluster that match a given TagSet
 * @ param tagSet a Set of replica set tags
 * @ return a List of ServerDescriptions of all the secondaries this cluster that match all of the given tags
 * @ deprecated Replace with a filter on ServerDescription in the caller */
@ Deprecated public List < ServerDescription > getSecondaries ( final TagSet tagSet ) { } }

implementation: return getServersByPredicate ( new Predicate ( ) { public boolean apply ( final ServerDescription serverDescription ) { return serverDescription . isSecondary ( ) && serverDescription . hasTags ( tagSet ) ; } } ) ;


signature:
public class ClusterDescription { /** * Gets a list of ServerDescriptions for all the servers in this cluster which are currently accessible .
 * @ return a List of ServerDescriptions for all servers that have a status of OK
 * @ deprecated Replace with a filter on ServerDescription in the caller */
@ Deprecated public List < ServerDescription > getAny ( ) { } }

implementation: return getServersByPredicate ( new Predicate ( ) { public boolean apply ( final ServerDescription serverDescription ) { return serverDescription . isOk ( ) ; } } ) ;


signature:
public class ClusterDescription { /** * Gets a list of all the primaries and secondaries in this cluster .
 * @ return a list of ServerDescriptions for all primary and secondary servers
 * @ deprecated Replace with a filter on ServerDescription in the caller */
@ Deprecated public List < ServerDescription > getAnyPrimaryOrSecondary ( ) { } }

implementation: return getServersByPredicate ( new Predicate ( ) { public boolean apply ( final ServerDescription serverDescription ) { return serverDescription . isPrimary ( ) || serverDescription . isSecondary ( ) ; } } ) ;


signature:
public class ClusterDescription { /** * Gets a list of all the primaries and secondaries in this cluster that match the given replica set tags .
 * @ param tagSet a Set of replica set tags
 * @ return a list of ServerDescriptions for all primary and secondary servers that contain all of the given tags
 * @ deprecated Replace with a filter on ServerDescription in the caller */
@ Deprecated public List < ServerDescription > getAnyPrimaryOrSecondary ( final TagSet tagSet ) { } }

implementation: return getServersByPredicate ( new Predicate ( ) { public boolean apply ( final ServerDescription serverDescription ) { return ( serverDescription . isPrimary ( ) || serverDescription . isSecondary ( ) ) && serverDescription . hasTags ( tagSet ) ; } } ) ;


signature:
public class ClusterDescription { /** * Returns a short , pretty description for this ClusterDescription .
 * @ return a String describing this cluster . */
public String getShortDescription ( ) { } }

implementation: StringBuilder serverDescriptions = new StringBuilder ( ) ; String delimiter = "" ; for ( final ServerDescription cur : this . serverDescriptions ) { serverDescriptions . append ( delimiter ) . append ( cur . getShortDescription ( ) ) ; delimiter = ", " ; } if ( srvResolutionException == null ) { return format ( "{type=%s, servers=[%s]" , type , serverDescriptions ) ; } else { return format ( "{type=%s, srvResolutionException=%s, servers=[%s]" , type , srvResolutionException , serverDescriptions ) ; }


signature:
public class MongoCredential { /** * Creates a MongoCredential instance with an unspecified mechanism . The client will negotiate the best mechanism based on the
 * version of the server that the client is authenticating to .
 * < p > If the server version is 4.0 or higher , the driver will negotiate with the server preferring the SCRAM - SHA - 256 mechanism . 3 . x
 * servers will authenticate using SCRAM - SHA - 1 , older servers will authenticate using the MONGODB _ CR mechanism . < / p >
 * @ param userName the user name
 * @ param database the database where the user is defined
 * @ param password the user ' s password
 * @ return the credential
 * @ since 2.13
 * @ mongodb . driver . manual core / authentication / # authentication - scram - sha - 256 SCRAM - SHA - 256
 * @ mongodb . driver . manual core / authentication / # authentication - scram - sha - 1 SCRAM - SHA - 1
 * @ mongodb . driver . manual core / authentication / # mongodb - cr - authentication MONGODB - CR */
public static MongoCredential createCredential ( final String userName , final String database , final char [ ] password ) { } }

implementation: return new MongoCredential ( null , userName , database , password ) ;


signature:
public class MongoCredential { /** * Creates a MongoCredential instance for the SCRAM - SHA - 1 SASL mechanism . Use this method only if you want to ensure that
 * the driver uses the SCRAM - SHA - 1 mechanism regardless of whether the server you are connecting to supports the
 * authentication mechanism . Otherwise use the { @ link # createCredential ( String , String , char [ ] ) } method to allow the driver to
 * negotiate the best mechanism based on the server version .
 * @ param userName the non - null user name
 * @ param source the source where the user is defined .
 * @ param password the non - null user password
 * @ return the credential
 * @ see # createCredential ( String , String , char [ ] )
 * @ since 2.13
 * @ mongodb . server . release 3.0
 * @ mongodb . driver . manual core / authentication / # authentication - scram - sha - 1 SCRAM - SHA - 1 */
public static MongoCredential createScramSha1Credential ( final String userName , final String source , final char [ ] password ) { } }

implementation: return new MongoCredential ( SCRAM_SHA_1 , userName , source , password ) ;


signature:
public class MongoCredential { /** * Creates a MongoCredential instance for the SCRAM - SHA - 256 SASL mechanism .
 * @ param userName the non - null user name
 * @ param source the source where the user is defined .
 * @ param password the non - null user password
 * @ return the credential
 * @ see # createCredential ( String , String , char [ ] )
 * @ since 3.8
 * @ mongodb . server . release 4.0
 * @ mongodb . driver . manual core / authentication / # authentication - scram - sha - 256 SCRAM - SHA - 256 */
public static MongoCredential createScramSha256Credential ( final String userName , final String source , final char [ ] password ) { } }

implementation: return new MongoCredential ( SCRAM_SHA_256 , userName , source , password ) ;


signature:
public class MongoCredential { /** * Creates a MongoCredential instance for the MongoDB Challenge Response protocol . Use this method only if you want to ensure that
 * the driver uses the MONGODB _ CR mechanism regardless of whether the server you are connecting to supports a more secure
 * authentication mechanism . Otherwise use the { @ link # createCredential ( String , String , char [ ] ) } method to allow the driver to
 * negotiate the best mechanism based on the server version .
 * @ param userName the user name
 * @ param database the database where the user is defined
 * @ param password the user ' s password
 * @ return the credential
 * @ see # createCredential ( String , String , char [ ] )
 * @ mongodb . driver . manual core / authentication / # mongodb - cr - authentication MONGODB - CR
 * @ deprecated MONGODB - CR was replaced by SCRAM - SHA - 1 in MongoDB 3.0 , and is now deprecated . Use
 * the { @ link # createCredential ( String , String , char [ ] ) } factory method instead . */
@ SuppressWarnings ( "deprecation" ) @ Deprecated public static MongoCredential createMongoCRCredential ( final String userName , final String database , final char [ ] password ) { } }

implementation: return new MongoCredential ( MONGODB_CR , userName , database , password ) ;


signature:
public class MongoCredential { /** * Creates a MongoCredential instance for the PLAIN SASL mechanism .
 * @ param userName the non - null user name
 * @ param source the source where the user is defined . This can be either { @ code " $ external " } or the name of a database .
 * @ param password the non - null user password
 * @ return the credential
 * @ since 2.12
 * @ mongodb . server . release 2.6
 * @ mongodb . driver . manual core / authentication / # ldap - proxy - authority - authentication PLAIN */
public static MongoCredential createPlainCredential ( final String userName , final String source , final char [ ] password ) { } }

implementation: return new MongoCredential ( PLAIN , userName , source , password ) ;