public <U> Codec<U> get(final Class<U> clazz) {
        if (hasCycles(clazz)) {
            return new LazyCodec<U>(registry, clazz);
        } else {
            return registry.get(new ChildCodecRegistry<U>(this, clazz));
        }
    }

public < U > Codec < U > get ( final Class < U > clazz ) { if ( hasCycles ( clazz ) ) { return new LazyCodec < U > ( registry , clazz ) ; } else { return registry . get ( new ChildCodecRegistry < U > ( this , clazz ) ) ; } }

Gets a Codec, but if it detects a cyclic dependency, return a LazyCodec which breaks the chain.

Gets a Codec but if it detects a cyclic dependency return a LazyCodec which breaks the chain .


public WriteResult insert(final DBObject document, final WriteConcern writeConcern) {
        return insert(asList(document), writeConcern);
    }

public WriteResult insert ( final DBObject document , final WriteConcern writeConcern ) { return insert ( asList ( document ) , writeConcern ) ; }

Insert a document into a collection. If the collection does not exists on the server, then it will be created. If the new document
does not contain an '_id' field, it will be added.

@param document     {@code DBObject} to be inserted
@param writeConcern {@code WriteConcern} to be used during operation
@return the result of the operation
@throws com.mongodb.DuplicateKeyException if the write failed to a duplicate unique key
@throws com.mongodb.WriteConcernException if the write failed due some other failure specific to the insert command
@throws MongoException if the operation failed for some other reason
@mongodb.driver.manual tutorial/insert-documents/ Insert Documents

Insert a document into a collection . If the collection does not exists on the server then it will be created . If the new document does not contain an _id field it will be added .


public WriteResult update(final DBObject query, final DBObject update, final DBCollectionUpdateOptions options) {
        notNull("query", query);
        notNull("update", update);
        notNull("options", options);
        WriteConcern writeConcern = options.getWriteConcern() != null ? options.getWriteConcern() : getWriteConcern();
        com.mongodb.bulk.WriteRequest.Type updateType = !update.keySet().isEmpty() && update.keySet().iterator().next().startsWith("$")
                                                                ? com.mongodb.bulk.WriteRequest.Type.UPDATE
                                                                : com.mongodb.bulk.WriteRequest.Type.REPLACE;
        UpdateRequest updateRequest = new UpdateRequest(wrap(query), wrap(update, options.getEncoder()), updateType)
                                              .upsert(options.isUpsert()).multi(options.isMulti())
                                              .collation(options.getCollation())
                                              .arrayFilters(wrapAllowNull(options.getArrayFilters(), options.getEncoder()));
        return executeWriteOperation(new UpdateOperation(getNamespace(), true, writeConcern, retryWrites,
                singletonList(updateRequest)).bypassDocumentValidation(options.getBypassDocumentValidation()));
    }

public WriteResult update ( final DBObject query , final DBObject update , final DBCollectionUpdateOptions options ) { notNull ( "query" , query ) ; notNull ( "update" , update ) ; notNull ( "options" , options ) ; WriteConcern writeConcern = options . getWriteConcern ( ) != null ? options . getWriteConcern ( ) : getWriteConcern ( ) ; com . mongodb . bulk . WriteRequest . Type updateType = ! update . keySet ( ) . isEmpty ( ) && update . keySet ( ) . iterator ( ) . next ( ) . startsWith ( "$" ) ? com . mongodb . bulk . WriteRequest . Type . UPDATE : com . mongodb . bulk . WriteRequest . Type . REPLACE ; UpdateRequest updateRequest = new UpdateRequest ( wrap ( query ) , wrap ( update , options . getEncoder ( ) ) , updateType ) . upsert ( options . isUpsert ( ) ) . multi ( options . isMulti ( ) ) . collation ( options . getCollation ( ) ) . arrayFilters ( wrapAllowNull ( options . getArrayFilters ( ) , options . getEncoder ( ) ) ) ; return executeWriteOperation ( new UpdateOperation ( getNamespace ( ) , true , writeConcern , retryWrites , singletonList ( updateRequest ) ) . bypassDocumentValidation ( options . getBypassDocumentValidation ( ) ) ) ; }

Modify an existing document or documents in collection.

@param query the selection criteria for the update
@param update the modifications to apply
@param options the options to apply to the update operation
@return the result of the operation
@throws com.mongodb.DuplicateKeyException if the write failed to a duplicate unique key
@throws com.mongodb.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 tutorial/modify-documents/ Modify
@since 3.4

Modify an existing document or documents in collection .


@Nullable
    public DBObject findOne(final Object id, final DBObject projection) {
        return findOne(new BasicDBObject("_id", id), new DBCollectionFindOptions().projection(projection));
    }

@ Nullable public DBObject findOne ( final Object id , final DBObject projection ) { return findOne ( new BasicDBObject ( "_id" , id ) , new DBCollectionFindOptions ( ) . projection ( projection ) ) ; }

Get a single document from collection by '_id'.

@param id         value of '_id' field of a document we are looking for
@param projection specifies which projection MongoDB will return from the documents in the result set.
@return A document that satisfies the query specified as the argument to this method.
@mongodb.driver.manual tutorial/query-documents/ Querying

Get a single document from collection by _id .


public DBCollection rename(final String newName, final boolean dropTarget) {
        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);
        }
    }

public DBCollection rename ( final String newName , final boolean dropTarget ) { 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 ) ; } }

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

Change the name of an existing collection .


public MapReduceOutput mapReduce(final String map, final String reduce, final String outputTarget,
                                     final MapReduceCommand.OutputType outputType, final DBObject query,
                                     final ReadPreference readPreference) {
        MapReduceCommand command = new MapReduceCommand(this, map, reduce, outputTarget, outputType, query);
        command.setReadPreference(readPreference);
        return mapReduce(command);
    }

public MapReduceOutput mapReduce ( final String map , final String reduce , final String outputTarget , final MapReduceCommand . OutputType outputType , final DBObject query , final ReadPreference readPreference ) { MapReduceCommand command = new MapReduceCommand ( this , map , reduce , outputTarget , outputType , query ) ; command . setReadPreference ( readPreference ) ; return mapReduce ( command ) ; }

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

Allows you to run map - reduce aggregation operations over a collection and saves to a named collection .


public CommandResult explainAggregate(final List<? extends DBObject> pipeline, final AggregationOptions options) {
        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()));
    }

public CommandResult explainAggregate ( final List < ? extends DBObject > pipeline , final AggregationOptions options ) { 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 ( ) ) ) ; }

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

Return the explain plan for the aggregation pipeline .


public void createIndex(final DBObject keys, @Nullable final String name, final boolean unique) {
        DBObject options = new BasicDBObject();
        if (name != null && name.length() > 0) {
            options.put("name", name);
        }
        if (unique) {
            options.put("unique", Boolean.TRUE);
        }
        createIndex(keys, options);
    }

public void createIndex ( final DBObject keys , @ Nullable final String name , final boolean unique ) { DBObject options = new BasicDBObject ( ) ; if ( name != null && name . length ( ) > 0 ) { options . put ( "name" , name ) ; } if ( unique ) { options . put ( "unique" , Boolean . TRUE ) ; } createIndex ( keys , options ) ; }

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

Forces creation of an index on a set of fields if one does not already exist .


public void createIndex(final DBObject keys, final DBObject options) {
        try {
            executor.execute(createIndexOperation(keys, options), getReadConcern());
        } catch (MongoWriteConcernException e) {
            throw createWriteConcernException(e);
        }
    }

public void createIndex ( final DBObject keys , final DBObject options ) { try { executor . execute ( createIndexOperation ( keys , options ) , getReadConcern ( ) ) ; } catch ( MongoWriteConcernException e ) { throw createWriteConcernException ( e ) ; } }

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

Creates an index on the field specified if that index does not already exist .


@Nullable
    public DBObject findAndRemove(@Nullable final DBObject query) {
        return findAndModify(query, null, null, true, null, false, false);
    }

@ Nullable public DBObject findAndRemove ( @ Nullable final DBObject query ) { return findAndModify ( query , null , null , true , null , false , false ) ; }

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

Atomically remove and return a single document . The returned document is the original document before removal .


public synchronized void setDBDecoderFactory(@Nullable final DBDecoderFactory factory) {
        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);
    }

Set a custom decoder factory for this collection.  Set to null to use the default from MongoOptions.

@param factory the factory to set.

Set a custom decoder factory for this collection . Set to null to use the default from MongoOptions .


public synchronized void setDBEncoderFactory(@Nullable final DBEncoderFactory factory) {
        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());
    }

Set a custom encoder factory for this collection.  Set to null to use the default from MongoOptions.

@param factory the factory to set.

Set a custom encoder factory for this collection . Set to null to use the default from MongoOptions .


public List<DBObject> getIndexInfo() {
        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>());
    }

public List < DBObject > getIndexInfo ( ) { 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 > ( ) ) ; }

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

Return a list of the indexes for this collection . Each object in the list is the info document from MongoDB


public void dropIndex(final DBObject index) {
        try {
            executor.execute(new DropIndexOperation(getNamespace(), wrap(index), getWriteConcern()), getReadConcern());
        } catch (MongoWriteConcernException e) {
            throw createWriteConcernException(e);
        }
    }

public void dropIndex ( final DBObject index ) { try { executor . execute ( new DropIndexOperation ( getNamespace ( ) , wrap ( index ) , getWriteConcern ( ) ) , getReadConcern ( ) ) ; } catch ( MongoWriteConcernException e ) { throw createWriteConcernException ( e ) ; } }

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

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 .


public void dropIndex(final String indexName) {
        try {
            executor.execute(new DropIndexOperation(getNamespace(), indexName, getWriteConcern()), getReadConcern());
        } catch (MongoWriteConcernException e) {
            throw createWriteConcernException(e);
        }
    }

public void dropIndex ( final String indexName ) { try { executor . execute ( new DropIndexOperation ( getNamespace ( ) , indexName , getWriteConcern ( ) ) , getReadConcern ( ) ) ; } catch ( MongoWriteConcernException e ) { throw createWriteConcernException ( e ) ; } }

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

Drops the index with the given name from this collection .


public boolean isCapped() {
        CommandResult commandResult = getStats();
        Object cappedField = commandResult.get("capped");
        return cappedField != null && (cappedField.equals(1) || cappedField.equals(true));
    }

public boolean isCapped ( ) { CommandResult commandResult = getStats ( ) ; Object cappedField = commandResult . get ( "capped" ) ; return cappedField != null && ( cappedField . equals ( 1 ) || cappedField . equals ( true ) ) ; }

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 void setInternalClass(final String path, final Class<? extends DBObject> aClass) {
        setObjectFactory(objectFactory.update(aClass, asList(path.split("\\."))));
    }

public void setInternalClass ( final String path , final Class < ? extends DBObject > aClass ) { setObjectFactory ( objectFactory . update ( aClass , asList ( path . split ( "\\." ) ) ) ) ; }

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


protected Class<? extends DBObject> getInternalClass(final String path) {
        return objectFactory.getClassForPath(asList(path.split("\\.")));
    }

protected Class < ? extends DBObject > getInternalClass ( final String path ) { return objectFactory . getClassForPath ( asList ( path . split ( "\\." ) ) ) ; }

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


public static <TItem> Bson set(final String fieldName, @Nullable final TItem value) {
        return new SimpleUpdate<TItem>(fieldName, value, "$set");
    }

public static < TItem > Bson set ( final String fieldName , @ Nullable final TItem value ) { return new SimpleUpdate < TItem > ( fieldName , value , "$set" ) ; }

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

Creates an update that sets the value of the field with the given name to the given value .


public static <TItem> Bson setOnInsert(final String fieldName, @Nullable final TItem value) {
        return new SimpleUpdate<TItem>(fieldName, value, "$setOnInsert");
    }

public static < TItem > Bson setOnInsert ( final String fieldName , @ Nullable final TItem value ) { return new SimpleUpdate < TItem > ( fieldName , value , "$setOnInsert" ) ; }

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)

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 .


public static Bson rename(final String fieldName, final String newFieldName) {
        notNull("newFieldName", newFieldName);
        return new SimpleUpdate<String>(fieldName, newFieldName, "$rename");
    }

public static Bson rename ( final String fieldName , final String newFieldName ) { notNull ( "newFieldName" , newFieldName ) ; return new SimpleUpdate < String > ( fieldName , newFieldName , "$rename" ) ; }

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

Creates an update that renames a field .


public static Bson inc(final String fieldName, final Number number) {
        notNull("number", number);
        return new SimpleUpdate<Number>(fieldName, number, "$inc");
    }

public static Bson inc ( final String fieldName , final Number number ) { notNull ( "number" , number ) ; return new SimpleUpdate < Number > ( fieldName , number , "$inc" ) ; }

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

Creates an update that increments the value of the field with the given name by the given value .


public static Bson mul(final String fieldName, final Number number) {
        notNull("number", number);
        return new SimpleUpdate<Number>(fieldName, number, "$mul");
    }

public static Bson mul ( final String fieldName , final Number number ) { notNull ( "number" , number ) ; return new SimpleUpdate < Number > ( fieldName , number , "$mul" ) ; }

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

Creates an update that multiplies the value of the field with the given name by the given number .


public static <TItem> Bson min(final String fieldName, final TItem value) {
        return new SimpleUpdate<TItem>(fieldName, value, "$min");
    }

public static < TItem > Bson min ( final String fieldName , final TItem value ) { return new SimpleUpdate < TItem > ( fieldName , value , "$min" ) ; }

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

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 .


public static <TItem> Bson max(final String fieldName, final TItem value) {
        return new SimpleUpdate<TItem>(fieldName, value, "$max");
    }

public static < TItem > Bson max ( final String fieldName , final TItem value ) { return new SimpleUpdate < TItem > ( fieldName , value , "$max" ) ; }

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

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 .


public static <TItem> Bson addToSet(final String fieldName, @Nullable final TItem value) {
        return new SimpleUpdate<TItem>(fieldName, value, "$addToSet");
    }

public static < TItem > Bson addToSet ( final String fieldName , @ Nullable final TItem value ) { return new SimpleUpdate < TItem > ( fieldName , value , "$addToSet" ) ; }

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

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


public static <TItem> Bson addEachToSet(final String fieldName, final List<TItem> values) {
        return new WithEachUpdate<TItem>(fieldName, values, "$addToSet");
    }

public static < TItem > Bson addEachToSet ( final String fieldName , final List < TItem > values ) { return new WithEachUpdate < TItem > ( fieldName , values , "$addToSet" ) ; }

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

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


public static <TItem> Bson push(final String fieldName, @Nullable final TItem value) {
        return new SimpleUpdate<TItem>(fieldName, value, "$push");
    }

public static < TItem > Bson push ( final String fieldName , @ Nullable final TItem value ) { return new SimpleUpdate < TItem > ( fieldName , value , "$push" ) ; }

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

Creates an update that adds the given value to the array value of the field with the given name .


public static <TItem> Bson pushEach(final String fieldName, final List<TItem> values) {
        return new PushUpdate<TItem>(fieldName, values, new PushOptions());
    }

public static < TItem > Bson pushEach ( final String fieldName , final List < TItem > values ) { return new PushUpdate < TItem > ( fieldName , values , new PushOptions ( ) ) ; }

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

Creates an update that adds each of the given values to the array value of the field with the given name .


public static <TItem> Bson pull(final String fieldName, @Nullable final TItem value) {
        return new SimpleUpdate<TItem>(fieldName, value, "$pull");
    }

public static < TItem > Bson pull ( final String fieldName , @ Nullable final TItem value ) { return new SimpleUpdate < TItem > ( fieldName , value , "$pull" ) ; }

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

Creates an update that removes all instances of the given value from the array value of the field with the given name .


public static Bson pullByFilter(final Bson filter) {
        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();
            }
        };
    }

public static Bson pullByFilter ( final Bson filter ) { 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 ( ) ; } } ; }

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

Creates an update that removes from an array all elements that match the given filter .


public static <TItem> Bson pullAll(final String fieldName, final List<TItem> values) {
        return new PullAllUpdate<TItem>(fieldName, values);
    }

public static < TItem > Bson pullAll ( final String fieldName , final List < TItem > values ) { return new PullAllUpdate < TItem > ( fieldName , values ) ; }

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

Creates an update that removes all instances of the given values from the array value of the field with the given name .


protected void writeQueryPrologue(final BsonOutput bsonOutput) {
        bsonOutput.writeInt32(getCursorFlag());
        bsonOutput.writeCString(getCollectionName());
        bsonOutput.writeInt32(skip);
        bsonOutput.writeInt32(numberToReturn);
    }

protected void writeQueryPrologue ( final BsonOutput bsonOutput ) { bsonOutput . writeInt32 ( getCursorFlag ( ) ) ; bsonOutput . writeCString ( getCollectionName ( ) ) ; bsonOutput . writeInt32 ( skip ) ; bsonOutput . writeInt32 ( numberToReturn ) ; }

Write the query prologue to the given BSON output.

@param bsonOutput the BSON output

Write the query prologue to the given BSON output .


private void incrementGenerationOnSocketException(final InternalConnection connection, final Throwable t) {
        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();
        }
    }

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

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 .


public static <T> List<Class<?>> getAncestry(final Class<T> clazz) {
        return ClassAncestry.getAncestry(clazz);
    }

public static < T > List < Class < ? > > getAncestry ( final Class < T > clazz ) { return ClassAncestry . getAncestry ( clazz ) ; }

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}.

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 .


@Deprecated
    public static ReplaceOptions createReplaceOptions(final UpdateOptions updateOptions) {
        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());
    }

@
Deprecated
public
static
ReplaceOptions
createReplaceOptions
(
final
UpdateOptions
updateOptions
)
{
notNull
(
"updateOptions"
,
updateOptions
)
;
List
<
extends
Bson
>
arrayFilters
=
updateOptions
.
getArrayFilters
(
)
;
isTrue
(
"ArrayFilters should be empty."
,
arrayFilters
==
||
arrayFilters
.
isEmpty
(
)
)
;
return
new
ReplaceOptions
(
)
.
bypassDocumentValidation
(
updateOptions
.
getBypassDocumentValidation
(
)
)
.
collation
(
updateOptions
.
getCollation
(
)
)
.
upsert
(
updateOptions
.
isUpsert
(
)
)
;
}

Creates replace options from updateOptions.

@param updateOptions the updateOptions
@return replace options
@deprecated there is no replacement for this method

Creates replace options from updateOptions .


public static byte[] decode(final String s) {
        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;
    }

public static byte [ ] decode ( final String s ) { 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 ; }

Decodes the given Base64-encoded string.

@param s the Base64-encoded string
@return the decoded byte array

Decodes the given Base64 - encoded string .


public static String encode(final byte[] in) {

        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);
    }

Encodes the given byte array into a Base64-encoded string.

@param in the byte array
@return the Base64-encoded string

Encodes the given byte array into a Base64 - encoded string .


@Deprecated
    @SuppressWarnings("deprecation")
    @Nullable
    public ServerAddress getAddress() {
        ClusterDescription description = getClusterDescription();
        if (description.getPrimaries().isEmpty()) {
            return null;
        }
        return description.getPrimaries().get(0).getAddress();
    }

@ Deprecated @ SuppressWarnings ( "deprecation" ) @ Nullable public ServerAddress getAddress ( ) { ClusterDescription description = getClusterDescription ( ) ; if ( description . getPrimaries ( ) . isEmpty ( ) ) { return null ; } return description . getPrimaries ( ) . get ( 0 ) . getAddress ( ) ; }

Gets the address of the current master

@return the address


@SuppressWarnings("deprecation")
    @Deprecated
    @Nullable
    public ReplicaSetStatus getReplicaSetStatus() {
        ClusterDescription clusterDescription = getClusterDescription();
        return clusterDescription.getType() == REPLICA_SET && clusterDescription.getConnectionMode() == MULTIPLE
               ? new ReplicaSetStatus(delegate.getCluster()) : null; // this is intended behavior in 2.x
    }

@
SuppressWarnings
(
"deprecation"
)
@
Deprecated
@
Nullable
public
ReplicaSetStatus
getReplicaSetStatus
(
)
{
ClusterDescription
clusterDescription
=
getClusterDescription
(
)
;
return
clusterDescription
.
getType
(
)
==
REPLICA_SET
&&
clusterDescription
.
getConnectionMode
(
)
==
MULTIPLE
new
ReplicaSetStatus
(
delegate
.
getCluster
(
)
)
:
;
// this is intended behavior in 2.x
}

Get the status of the replica set cluster.

@return replica set status information

Get the status of the replica set cluster .


@Deprecated
    public List<String> getDatabaseNames() {
        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>());
    }

@ Deprecated public List < String > getDatabaseNames ( ) { 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 > ( ) ) ; }

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()}

Gets a list of the names of all databases on the connected server .


@Deprecated
    public CommandResult fsync(final boolean async) {
        DBObject command = new BasicDBObject("fsync", 1);
        if (async) {
            command.put("async", 1);
        }
        return getDB(ADMIN_DATABASE_NAME).command(command);
    }

@ Deprecated public CommandResult fsync ( final boolean async ) { DBObject command = new BasicDBObject ( "fsync" , 1 ) ; if ( async ) { command . put ( "async" , 1 ) ; } return getDB ( ADMIN_DATABASE_NAME ) . command ( command ) ; }

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

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 .


@Deprecated
    public CommandResult fsyncAndLock() {
        DBObject command = new BasicDBObject("fsync", 1);
        command.put("lock", 1);
        return getDB(ADMIN_DATABASE_NAME).command(command);
    }

@ Deprecated public CommandResult fsyncAndLock ( ) { DBObject command = new BasicDBObject ( "fsync" , 1 ) ; command . put ( "lock" , 1 ) ; return getDB ( ADMIN_DATABASE_NAME ) . command ( command ) ; }

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

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 .


@Deprecated
    public DBObject unlock() {
        return DBObjects.toDBObject(createOperationExecutor().execute(new FsyncUnlockOperation(), readPreference, readConcern));
    }

@ Deprecated public DBObject unlock ( ) { return DBObjects . toDBObject ( createOperationExecutor ( ) . execute ( new FsyncUnlockOperation ( ) , readPreference , readConcern ) ) ; }

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

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 .


public BsonNumber asNumber() {
        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;
    }

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

Gets this value as a BsonNumber if it is one otherwise throws exception


public ConnectionId withServerValue(final int serverValue) {
        isTrue("server value is null", this.serverValue == null);
        return new ConnectionId(serverId, localValue, serverValue);
    }

public
ConnectionId
withServerValue
(
final
int
serverValue
)
{
isTrue
(
"server value is null"
,
this
.
serverValue
==
)
;
return
new
ConnectionId
(
serverId
,
localValue
,
serverValue
)
;
}

Creates a new connectionId with the set server value

@param serverValue the server value
@return the new connection id
@since 3.8


private static List<Class<?>> computeAncestry(final Class<?> c) {
        List<Class<?>> result = new ArrayList<Class<?>>();
        result.add(Object.class);
        computeAncestry(c, result);
        Collections.reverse(result);
        return unmodifiableList(new ArrayList<Class<?>>(result));
    }

private static List < Class < ? > > computeAncestry ( final Class < ? > c ) { List < Class < ? > > result = new ArrayList < Class < ? > > ( ) ; result . add ( Object . class ) ; computeAncestry ( c , result ) ; Collections . reverse ( result ) ; return unmodifiableList ( new ArrayList < Class < ? > > ( result ) ) ; }

Starting with children and going back to parents


@SuppressWarnings({"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();
    }

@ SuppressWarnings ( { "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 ( ) ; }

Converts to GeoJSON representation

@return the GeoJSON representation


@Override
    @SuppressWarnings("unchecked")
    public MapReduceBatchCursor<T> execute(final ReadBinding binding) {
        return executeCommand(binding, namespace.getDatabaseName(), getCommandCreator(binding.getSessionContext()),
                CommandResultDocumentCodec.create(decoder, "results"), transformer(), false);
    }

@ Override @ SuppressWarnings ( "unchecked" ) public MapReduceBatchCursor < T > execute ( final ReadBinding binding ) { return executeCommand ( binding , namespace . getDatabaseName ( ) , getCommandCreator ( binding . getSessionContext ( ) ) , CommandResultDocumentCodec . create ( decoder , "results" ) , transformer ( ) , false ) ; }

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.

Executing this will return a cursor with your results and the statistics in .


@Nullable
    public Long getExpireAfter(final TimeUnit timeUnit) {
        if (expireAfterSeconds == null) {
            return null;
        }
        return timeUnit.convert(expireAfterSeconds, TimeUnit.SECONDS);
    }

@ Nullable public Long getExpireAfter ( final TimeUnit timeUnit ) { if ( expireAfterSeconds == null ) { return null ; } return timeUnit . convert ( expireAfterSeconds , TimeUnit . SECONDS ) ; }

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


public DBObject toDBObject() {
        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);
    }

public DBObject toDBObject ( ) { 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 ) ; }

Turns this group command into the DBObject format of the command.

@return a DBObject containing the group command as a MongoDB document

Turns this group command into the DBObject format of the command .


public Integer getLogicalSessionTimeoutMinutes() {
        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;
    }

public Integer getLogicalSessionTimeoutMinutes ( ) { 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 ; }

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

Gets the logical session timeout in minutes or null if at least one of the known servers does not support logical sessions .


@Deprecated
    public Set<ServerDescription> getAll() {
        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);
    }

@ Deprecated public Set < ServerDescription > getAll ( ) { 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 ) ; }

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

Returns the Set of all server descriptions in this cluster sorted by the String value of the ServerAddress of each one .


@Deprecated
    public ServerDescription getByServerAddress(final ServerAddress serverAddress) {
        for (final ServerDescription cur : serverDescriptions) {
            if (cur.isOk() && cur.getAddress().equals(serverAddress)) {
                return cur;
            }
        }
        return null;
    }

@ Deprecated public ServerDescription getByServerAddress ( final ServerAddress serverAddress ) { for ( final ServerDescription cur : serverDescriptions ) { if ( cur . isOk ( ) && cur . getAddress ( ) . equals ( serverAddress ) ) { return cur ; } } return null ; }

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 List<ServerDescription> getPrimaries() {
        return getServersByPredicate(new Predicate() {
            public boolean apply(final ServerDescription serverDescription) {
                return serverDescription.isPrimary();
            }
        });
    }

@ Deprecated public List < ServerDescription > getPrimaries ( ) { return getServersByPredicate ( new Predicate ( ) { public boolean apply ( final ServerDescription serverDescription ) { return serverDescription . isPrimary ( ) ; } } ) ; }

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

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 .


@Deprecated
    public List<ServerDescription> getSecondaries() {
        return getServersByPredicate(new Predicate() {
            public boolean apply(final ServerDescription serverDescription) {
                return serverDescription.isSecondary();
            }
        });
    }

@ Deprecated public List < ServerDescription > getSecondaries ( ) { return getServersByPredicate ( new Predicate ( ) { public boolean apply ( final ServerDescription serverDescription ) { return serverDescription . isSecondary ( ) ; } } ) ; }

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(final TagSet tagSet) {
        return getServersByPredicate(new Predicate() {
            public boolean apply(final ServerDescription serverDescription) {
                return serverDescription.isSecondary() && serverDescription.hasTags(tagSet);
            }
        });
    }

@ Deprecated public List < ServerDescription > getSecondaries ( final TagSet tagSet ) { return getServersByPredicate ( new Predicate ( ) { public boolean apply ( final ServerDescription serverDescription ) { return serverDescription . isSecondary ( ) && serverDescription . hasTags ( tagSet ) ; } } ) ; }

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> getAny() {
        return getServersByPredicate(new Predicate() {
            public boolean apply(final ServerDescription serverDescription) {
                return serverDescription.isOk();
            }
        });
    }

@ Deprecated public List < ServerDescription > getAny ( ) { return getServersByPredicate ( new Predicate ( ) { public boolean apply ( final ServerDescription serverDescription ) { return serverDescription . isOk ( ) ; } } ) ; }

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

Gets a list of ServerDescriptions for all the servers in this cluster which are currently accessible .


@Deprecated
    public List<ServerDescription> getAnyPrimaryOrSecondary() {
        return getServersByPredicate(new Predicate() {
            public boolean apply(final ServerDescription serverDescription) {
                return serverDescription.isPrimary() || serverDescription.isSecondary();
            }
        });
    }

@ Deprecated public List < ServerDescription > getAnyPrimaryOrSecondary ( ) { return getServersByPredicate ( new Predicate ( ) { public boolean apply ( final ServerDescription serverDescription ) { return serverDescription . isPrimary ( ) || serverDescription . isSecondary ( ) ; } } ) ; }

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

Gets a list of all the primaries and secondaries in this cluster .


@Deprecated
    public List<ServerDescription> getAnyPrimaryOrSecondary(final TagSet tagSet) {
        return getServersByPredicate(new Predicate() {
            public boolean apply(final ServerDescription serverDescription) {
                return (serverDescription.isPrimary() || serverDescription.isSecondary()) && serverDescription.hasTags(tagSet);
            }
        });
    }

@ Deprecated public List < ServerDescription > getAnyPrimaryOrSecondary ( final TagSet tagSet ) { return getServersByPredicate ( new Predicate ( ) { public boolean apply ( final ServerDescription serverDescription ) { return ( serverDescription . isPrimary ( ) || serverDescription . isSecondary ( ) ) && serverDescription . hasTags ( tagSet ) ; } } ) ; }

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

Gets a list of all the primaries and secondaries in this cluster that match the given replica set tags .


public String getShortDescription() {
        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);
        }
    }

Returns a short, pretty description for this ClusterDescription.

@return a String describing this cluster.

Returns a short pretty description for this ClusterDescription .


public static MongoCredential createCredential(final String userName, final String database, final char[] password) {
        return new MongoCredential(null, userName, database, password);
    }

public static MongoCredential createCredential ( final String userName , final String database , final char [ ] password ) { return new MongoCredential ( null , userName , database , password ) ; }

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.

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.

@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

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 .


public static MongoCredential createScramSha256Credential(final String userName, final String source, final char[] password) {
        return new MongoCredential(SCRAM_SHA_256, userName, source, password);
    }

public static MongoCredential createScramSha256Credential ( final String userName , final String source , final char [ ] password ) { return new MongoCredential ( SCRAM_SHA_256 , userName , source , password ) ; }

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

Creates a MongoCredential instance for the SCRAM - SHA - 256 SASL mechanism .


public static MongoCredential createPlainCredential(final String userName, final String source, final char[] password) {
        return new MongoCredential(PLAIN, userName, source, password);
    }

public static MongoCredential createPlainCredential ( final String userName , final String source , final char [ ] password ) { return new MongoCredential ( PLAIN , userName , source , password ) ; }

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

Creates a MongoCredential instance for the PLAIN SASL mechanism .


public <T> MongoCredential withMechanismProperty(final String key, final T value) {
        return new MongoCredential(this, key, value);
    }

public < T > MongoCredential withMechanismProperty ( final String key , final T value ) { return new MongoCredential ( this , key , value ) ; }

Creates a new MongoCredential as a copy of this instance, with the specified mechanism property added.

@param key   the key to the property, which is treated as case-insensitive
@param value the value of the property
@param <T>   the property type
@return the credential
@since 2.12

Creates a new MongoCredential as a copy of this instance with the specified mechanism property added .


public MongoCredential withMechanism(final AuthenticationMechanism mechanism) {
        if (this.mechanism != null) {
            throw new IllegalArgumentException("Mechanism already set");
        }
        return new MongoCredential(mechanism, userName, source, password, mechanismProperties);
    }

public
MongoCredential
withMechanism
(
final
AuthenticationMechanism
mechanism
)
{
if
(
this
.
mechanism
!=
)
{
throw
new
IllegalArgumentException
(
"Mechanism already set"
)
;
}
return
new
MongoCredential
(
mechanism
,
userName
,
source
,
password
,
mechanismProperties
)
;
}

Creates a new MongoCredential with the set mechanism. The existing mechanism must be null.

@param mechanism the mechanism to set
@return the credential
@since 3.8

Creates a new MongoCredential with the set mechanism . The existing mechanism must be null .


@SuppressWarnings("unchecked")
    @Nullable
    public <T> T getMechanismProperty(final String key, @Nullable final T defaultValue) {
        notNull("key", key);

        T value = (T) mechanismProperties.get(key.toLowerCase());
        return (value == null) ? defaultValue : value;

    }

@ SuppressWarnings ( "unchecked" ) @ Nullable public < T > T getMechanismProperty ( final String key , @ Nullable final T defaultValue ) { notNull ( "key" , key ) ; T value = ( T ) mechanismProperties . get ( key . toLowerCase ( ) ) ; return ( value == null ) ? defaultValue : value ; }

Get the value of the given key to a mechanism property, or defaultValue if there is no mapping.

@param key          the mechanism property key, which is treated as case-insensitive
@param defaultValue the default value, if no mapping exists
@param <T>          the value type
@return the mechanism property value
@since 2.12

Get the value of the given key to a mechanism property or defaultValue if there is no mapping .


public byte[] toByteArray() {
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream(size());
            pipe(bout);
            return bout.toByteArray();
        } catch (IOException ioe) {
            throw new RuntimeException("should be impossible", ioe);
        }
    }

public
byte
[
]
toByteArray
(
)
{
try
{
ByteArrayOutputStream
bout
=
new
ByteArrayOutputStream
(
size
(
)
)
;
pipe
(
bout
)
;
return
bout
.
toByteArray
(
)
;
}
catch
(
IOException
ioe
)
{
throw
new
RuntimeException
(
"should be impossible"
,
ioe
)
;
}
}

Gets a copy of the buffered bytes.

@return the byte array
@see org.bson.io.OutputBuffer#pipe(java.io.OutputStream)


@SuppressWarnings("rawtypes")
    void addObjectSerializer(final Class c, final ObjectSerializer serializer) {
        _serializers.put(c, serializer);
    }

@ SuppressWarnings ( "rawtypes" ) void addObjectSerializer ( final Class c , final ObjectSerializer serializer ) { _serializers . put ( c , serializer ) ; }

Assign a ObjectSerializer to perform a type specific serialization scheme

@param c          this object's type serves as a key in the serialization map. ClassMapBasedObjectSerializer uses
org.bson.util.ClassMap and not only checks if 'c' is a key in the Map, but also walks the up superclass and
interface graph of 'c' to find matches. This means that it is only necessary assign ObjectSerializers to base
classes. @see org.bson.util.ClassMap
@param serializer performs the serialization mapping specific to the @param key type


public UpdateRequest multi(final boolean isMulti) {
        if (isMulti && updateType == Type.REPLACE) {
            throw new IllegalArgumentException("Replacements can not be multi");
        }
        this.isMulti = isMulti;
        return this;
    }

public
UpdateRequest
multi
(
final
boolean
isMulti
)
{
if
(
isMulti
&&
updateType
==
Type
.
REPLACE
)
{
throw
new
IllegalArgumentException
(
"Replacements can not be multi"
)
;
}
this
.
isMulti
=
isMulti
;
return
this
;
}

Sets whether this will update all documents matching the query filter.

@param isMulti whether this will update all documents matching the query filter
@return this

Sets whether this will update all documents matching the query filter .


public void encode(final BsonOutput bsonOutput, final SessionContext sessionContext) {
        notNull("sessionContext", sessionContext);
        int messageStartPosition = bsonOutput.getPosition();
        writeMessagePrologue(bsonOutput);
        EncodingMetadata encodingMetadata = encodeMessageBodyWithMetadata(bsonOutput, sessionContext);
        backpatchMessageLength(messageStartPosition, bsonOutput);
        this.encodingMetadata = encodingMetadata;
    }

public void encode ( final BsonOutput bsonOutput , final SessionContext sessionContext ) { notNull ( "sessionContext" , sessionContext ) ; int messageStartPosition = bsonOutput . getPosition ( ) ; writeMessagePrologue ( bsonOutput ) ; EncodingMetadata encodingMetadata = encodeMessageBodyWithMetadata ( bsonOutput , sessionContext ) ; backpatchMessageLength ( messageStartPosition , bsonOutput ) ; this . encodingMetadata = encodingMetadata ; }

Encoded the message to the given output.

@param bsonOutput the output
@param sessionContext the session context

Encoded the message to the given output .


protected void writeMessagePrologue(final BsonOutput bsonOutput) {
        bsonOutput.writeInt32(0); // length: will set this later
        bsonOutput.writeInt32(id);
        bsonOutput.writeInt32(0); // response to
        bsonOutput.writeInt32(opCode.getValue());
    }

protected
void
writeMessagePrologue
(
final
BsonOutput
bsonOutput
)
{
bsonOutput
.
writeInt32
(
0
)
;
// length: will set this later
bsonOutput
.
writeInt32
(
id
)
;
bsonOutput
.
writeInt32
(
0
)
;
// response to
bsonOutput
.
writeInt32
(
opCode
.
getValue
(
)
)
;
}

Writes the message prologue to the given output.

@param bsonOutput the output

Writes the message prologue to the given output .


protected void addDocument(final BsonDocument document, final BsonOutput bsonOutput,
                               final FieldNameValidator validator) {
        addDocument(document, getCodec(document), EncoderContext.builder().build(), bsonOutput, validator,
                    settings.getMaxDocumentSize() + DOCUMENT_HEADROOM, null);
    }

protected void addDocument ( final BsonDocument document , final BsonOutput bsonOutput , final FieldNameValidator validator ) { addDocument ( document , getCodec ( document ) , EncoderContext . builder ( ) . build ( ) , bsonOutput , validator , settings . getMaxDocumentSize ( ) + DOCUMENT_HEADROOM , null ) ; }

Appends a document to the message.

@param document the document
@param bsonOutput the output
@param validator the field name validator


protected void addCollectibleDocument(final BsonDocument document, final BsonOutput bsonOutput, final FieldNameValidator validator) {
        addDocument(document, getCodec(document), EncoderContext.builder().isEncodingCollectibleDocument(true).build(), bsonOutput,
                    validator, settings.getMaxDocumentSize(), null);
    }

protected void addCollectibleDocument ( final BsonDocument document , final BsonOutput bsonOutput , final FieldNameValidator validator ) { addDocument ( document , getCodec ( document ) , EncoderContext . builder ( ) . isEncodingCollectibleDocument ( true ) . build ( ) , bsonOutput , validator , settings . getMaxDocumentSize ( ) , null ) ; }

Appends a document to the message that is intended for storage in a collection.

@param document the document
@param bsonOutput the output
@param validator the field name validator

Appends a document to the message that is intended for storage in a collection .


protected void backpatchMessageLength(final int startPosition, final BsonOutput bsonOutput) {
        int messageLength = bsonOutput.getPosition() - startPosition;
        bsonOutput.writeInt32(bsonOutput.getPosition() - messageLength, messageLength);
    }

protected void backpatchMessageLength ( final int startPosition , final BsonOutput bsonOutput ) { int messageLength = bsonOutput . getPosition ( ) - startPosition ; bsonOutput . writeInt32 ( bsonOutput . getPosition ( ) - messageLength , messageLength ) ; }

Backpatches the message length into the beginning of the message.

@param startPosition the start position of the message
@param bsonOutput the output

Backpatches the message length into the beginning of the message .


protected DBObject createChunk(final Object id, final int currentChunkNumber, final byte[] writeBuffer) {
        return new BasicDBObject("files_id", id)
               .append("n", currentChunkNumber)
               .append("data", writeBuffer);
    }

protected DBObject createChunk ( final Object id , final int currentChunkNumber , final byte [ ] writeBuffer ) { return new BasicDBObject ( "files_id" , id ) . append ( "n" , currentChunkNumber ) . append ( "data" , writeBuffer ) ; }

Creates a new chunk of this file. Can be over-ridden, if input files need to be split into chunks using a different mechanism.

@param id                 the file ID
@param currentChunkNumber the unique id for this chunk
@param writeBuffer        the byte array containing the data for this chunk
@return a DBObject representing this chunk.

Creates a new chunk of this file . Can be over - ridden if input files need to be split into chunks using a different mechanism .


public DBCursor copy() {
        return new DBCursor(collection, filter, findOptions, executor, decoderFactory, decoder, retryReads);
    }

public DBCursor copy ( ) { return new DBCursor ( collection , filter , findOptions , executor , decoderFactory , decoder , retryReads ) ; }

Creates a copy of an existing database cursor. The new cursor is an iterator, even if the original was an array.

@return the new cursor

Creates a copy of an existing database cursor . The new cursor is an iterator even if the original was an array .


@Override
    public boolean hasNext() {
        if (closed) {
            throw new IllegalStateException("Cursor has been closed");
        }

        if (cursor == null) {
            FindOperation<DBObject> operation = getQueryOperation(decoder);
            if (operation.getCursorType() == CursorType.Tailable) {
                operation.cursorType(CursorType.TailableAwait);
            }
            initializeCursor(operation);
        }

        boolean hasNext = cursor.hasNext();
        setServerCursorOnFinalizer(cursor.getServerCursor());
        return hasNext;
    }

@
Override
public
boolean
hasNext
(
)
{
if
(
closed
)
{
throw
new
IllegalStateException
(
"Cursor has been closed"
)
;
}
if
(
cursor
==
)
{
FindOperation
<
DBObject
>
operation
=
getQueryOperation
(
decoder
)
;
if
(
operation
.
getCursorType
(
)
==
CursorType
.
Tailable
)
{
operation
.
cursorType
(
CursorType
.
TailableAwait
)
;
}
initializeCursor
(
operation
)
;
}
boolean
hasNext
=
cursor
.
hasNext
(
)
;
setServerCursorOnFinalizer
(
cursor
.
getServerCursor
(
)
)
;
return
hasNext
;
}

Checks if there is another object available.

Note: Automatically adds the {@link Bytes#QUERYOPTION_AWAITDATA} option to any cursors with the
{@link Bytes#QUERYOPTION_TAILABLE} option set. For non blocking tailable cursors see {@link #tryNext }.

@return true if there is another object available
@mongodb.driver.manual /core/cursors/#cursor-batches Cursor Batches

Checks if there is another object available .


@Nullable
    public DBObject tryNext() {
        if (cursor == null) {
            FindOperation<DBObject> operation = getQueryOperation(decoder);
            if (!operation.getCursorType().isTailable()) {
                throw new IllegalArgumentException("Can only be used with a tailable cursor");
            }
            initializeCursor(operation);
        }
        DBObject next = cursor.tryNext();
        setServerCursorOnFinalizer(cursor.getServerCursor());
        return currentObject(next);
    }

Non blocking check for tailable cursors to see if another object is available.

Returns the object the cursor is at and moves the cursor ahead by one or
return null if no documents is available.

@return the next element or null
@throws MongoException if failed
@throws IllegalArgumentException if the cursor is not tailable
@mongodb.driver.manual /core/cursors/#cursor-batches Cursor Batches

Non blocking check for tailable cursors to see if another object is available .


public List<DBObject> toArray(final int max) {
        checkIteratorOrArray(IteratorOrArray.ARRAY);
        fillArray(max - 1);
        return all;
    }

public List < DBObject > toArray ( final int max ) { checkIteratorOrArray ( IteratorOrArray . ARRAY ) ; fillArray ( max - 1 ) ; return all ; }

Converts this cursor to an array.

@param max the maximum number of objects to return
@return an array of objects
@throws MongoException if failed


@Nullable
    public DBObject one() {
        DBCursor findOneCursor = copy().limit(-1);
        try {
            return findOneCursor.hasNext() ? findOneCursor.next() : null;
        } finally {
            findOneCursor.close();
        }
    }

@ Nullable public DBObject one ( ) { DBCursor findOneCursor = copy ( ) . limit ( - 1 ) ; try { return findOneCursor . hasNext ( ) ? findOneCursor . next ( ) : null ; } finally { findOneCursor . close ( ) ; } }

Returns the first document that matches the query.

@return the first matching document
@since 2.12

Returns the first document that matches the query .


public ReadPreference getReadPreference() {
        ReadPreference readPreference = findOptions.getReadPreference();
        if (readPreference != null) {
            return readPreference;
        }
        return collection.getReadPreference();
    }

public ReadPreference getReadPreference ( ) { ReadPreference readPreference = findOptions . getReadPreference ( ) ; if ( readPreference != null ) { return readPreference ; } return collection . getReadPreference ( ) ; }

Gets the default read preference.

@return the readPreference used by this cursor


ReadConcern getReadConcern() {
        ReadConcern readConcern = findOptions.getReadConcern();
        if (readConcern != null) {
            return readConcern;
        }
        return collection.getReadConcern();
    }

ReadConcern getReadConcern ( ) { ReadConcern readConcern = findOptions . getReadConcern ( ) ; if ( readConcern != null ) { return readConcern ; } return collection . getReadConcern ( ) ; }

Get the read concern for this collection.

@return the {@link com.mongodb.ReadConcern}
@since 3.2
@mongodb.server.release 3.2
@mongodb.driver.manual reference/readConcern/ Read Concern

Get the read concern for this collection .


protected void _put(final String name, final Object value) {
        cur().put(name, !BSON.hasDecodeHooks() ? value : BSON.applyDecodingHooks(value));
    }

protected void _put ( final String name , final Object value ) { cur ( ) . put ( name , ! BSON . hasDecodeHooks ( ) ? value : BSON . applyDecodingHooks ( value ) ) ; }

Puts a new value into the document.

@param name  the name of the field
@param value the value


protected void putDBRef(final String name, final DBRef ref) {
        BasicDBObject dbRefDocument = new BasicDBObject("$ref", ref.getCollectionName()).append("$id", ref.getId());
        if (ref.getDatabaseName() != null) {
            dbRefDocument.put("$db", ref.getDatabaseName());
        }

        putObject(name, dbRefDocument);
    }

protected void putDBRef ( final String name , final DBRef ref ) { BasicDBObject dbRefDocument = new BasicDBObject ( "$ref" , ref . getCollectionName ( ) ) . append ( "$id" , ref . getId ( ) ) ; if ( ref . getDatabaseName ( ) != null ) { dbRefDocument . put ( "$db" , ref . getDatabaseName ( ) ) ; } putObject ( name , dbRefDocument ) ; }

Deals with encoding database references.

@param name the name of the field in the document
@param ref  the database reference object

Deals with encoding database references .


public static BulkWriteResult unacknowledged() {
        return new BulkWriteResult() {
            @Override
            public boolean wasAcknowledged() {
                return false;
            }

            @Override
            public int getInsertedCount() {
                throw getUnacknowledgedWriteException();
            }

            @Override
            public int getMatchedCount() {
                throw getUnacknowledgedWriteException();
            }

            @Override
            public int getDeletedCount() {
                throw getUnacknowledgedWriteException();
            }

            @Override
            @Deprecated
            public boolean isModifiedCountAvailable() {
                throw getUnacknowledgedWriteException();
            }

            @Override
            public int getModifiedCount() {
                throw getUnacknowledgedWriteException();
            }

            @Override
            public List<BulkWriteUpsert> getUpserts() {
                throw getUnacknowledgedWriteException();
            }

            @Override
            public boolean equals(final Object o) {
                if (this == o) {
                    return true;
                }
                if (o == null || getClass() != o.getClass()) {
                    return false;
                }

                BulkWriteResult that = (BulkWriteResult) o;
                return !that.wasAcknowledged();
            }

            @Override
            public int hashCode() {
                return 0;
            }

            @Override
            public String toString() {
                return "UnacknowledgedBulkWriteResult{}";
            }

            private UnsupportedOperationException getUnacknowledgedWriteException() {
                return new UnsupportedOperationException("Cannot get information about an unacknowledged write");
            }
        };
    }

Create an unacknowledged BulkWriteResult

@return an unacknowledged BulkWriteResult


public InetSocketAddress getSocketAddress() {
        try {
            return new InetSocketAddress(InetAddress.getByName(host), port);
        } catch (UnknownHostException e) {
            throw new MongoSocketException(e.getMessage(), this, e);
        }
    }

public InetSocketAddress getSocketAddress ( ) { try { return new InetSocketAddress ( InetAddress . getByName ( host ) , port ) ; } catch ( UnknownHostException e ) { throw new MongoSocketException ( e . getMessage ( ) , this , e ) ; } }

Gets the underlying socket address

@return socket address


public List<InetSocketAddress> getSocketAddresses() {
        try {
            InetAddress[] inetAddresses = InetAddress.getAllByName(host);
            List<InetSocketAddress> inetSocketAddressList = new ArrayList<InetSocketAddress>();
            for (InetAddress inetAddress : inetAddresses) {
                inetSocketAddressList.add(new InetSocketAddress(inetAddress, port));
            }

            return inetSocketAddressList;
        } catch (UnknownHostException e) {
            throw new MongoSocketException(e.getMessage(), this, e);
        }
    }

public List < InetSocketAddress > getSocketAddresses ( ) { try { InetAddress [ ] inetAddresses = InetAddress . getAllByName ( host ) ; List < InetSocketAddress > inetSocketAddressList = new ArrayList < InetSocketAddress > ( ) ; for ( InetAddress inetAddress : inetAddresses ) { inetSocketAddressList . add ( new InetSocketAddress ( inetAddress , port ) ) ; } return inetSocketAddressList ; } catch ( UnknownHostException e ) { throw new MongoSocketException ( e . getMessage ( ) , this , e ) ; } }

Gets all underlying socket addresses

@return array of socket addresses

@since 3.9


public static <TItem> Bson ne(final String fieldName, @Nullable final TItem value) {
        return new OperatorFilter<TItem>("$ne", fieldName, value);
    }

public static < TItem > Bson ne ( final String fieldName , @ Nullable final TItem value ) { return new OperatorFilter < TItem > ( "$ne" , fieldName , value ) ; }

Creates a filter that matches all documents where the value of the field name does not equal the specified value.

@param fieldName the field name
@param value     the value, which may be null
@param <TItem>   the value type
@return the filter
@mongodb.driver.manual reference/operator/query/ne $ne

Creates a filter that matches all documents where the value of the field name does not equal the specified value .


public static <TItem> Bson gt(final String fieldName, final TItem value) {
        return new OperatorFilter<TItem>("$gt", fieldName, value);
    }

public static < TItem > Bson gt ( final String fieldName , final TItem value ) { return new OperatorFilter < TItem > ( "$gt" , fieldName , value ) ; }

Creates a filter that matches all documents where the value of the given field is greater than the specified value.

@param fieldName the field name
@param value     the value
@param <TItem>   the value type
@return the filter
@mongodb.driver.manual reference/operator/query/gt $gt

Creates a filter that matches all documents where the value of the given field is greater than the specified value .


public static <TItem> Bson lt(final String fieldName, final TItem value) {
        return new OperatorFilter<TItem>("$lt", fieldName, value);
    }

public static < TItem > Bson lt ( final String fieldName , final TItem value ) { return new OperatorFilter < TItem > ( "$lt" , fieldName , value ) ; }

Creates a filter that matches all documents where the value of the given field is less than the specified value.

@param fieldName the field name
@param value     the value
@param <TItem>   the value type
@return the filter
@mongodb.driver.manual reference/operator/query/lt $lt

Creates a filter that matches all documents where the value of the given field is less than the specified value .


public static <TItem> Bson gte(final String fieldName, final TItem value) {
        return new OperatorFilter<TItem>("$gte", fieldName, value);
    }

public static < TItem > Bson gte ( final String fieldName , final TItem value ) { return new OperatorFilter < TItem > ( "$gte" , fieldName , value ) ; }

Creates a filter that matches all documents where the value of the given field is greater than or equal to the specified value.

@param fieldName the field name
@param value     the value
@param <TItem>   the value type
@return the filter
@mongodb.driver.manual reference/operator/query/gte $gte

Creates a filter that matches all documents where the value of the given field is greater than or equal to the specified value .


public static <TItem> Bson lte(final String fieldName, final TItem value) {
        return new OperatorFilter<TItem>("$lte", fieldName, value);
    }

public static < TItem > Bson lte ( final String fieldName , final TItem value ) { return new OperatorFilter < TItem > ( "$lte" , fieldName , value ) ; }

Creates a filter that matches all documents where the value of the given field is less than or equal to the specified value.

@param fieldName the field name
@param value     the value
@param <TItem>   the value type
@return the filter
@mongodb.driver.manual reference/operator/query/lte $lte

Creates a filter that matches all documents where the value of the given field is less than or equal to the specified value .


public static Bson or(final Iterable<Bson> filters) {
        return new OrNorFilter(OrNorFilter.Operator.OR, filters);
    }

public static Bson or ( final Iterable < Bson > filters ) { return new OrNorFilter ( OrNorFilter . Operator . OR , filters ) ; }

Creates a filter that preforms a logical OR of the provided list of filters.

@param filters the list of filters to and together
@return the filter
@mongodb.driver.manual reference/operator/query/or $or

Creates a filter that preforms a logical OR of the provided list of filters .


public static Bson nor(final Iterable<Bson> filters) {
        return new OrNorFilter(OrNorFilter.Operator.NOR, filters);
    }

public static Bson nor ( final Iterable < Bson > filters ) { return new OrNorFilter ( OrNorFilter . Operator . NOR , filters ) ; }

Creates a filter that performs a logical NOR operation on all the specified filters.

@param filters the list of values
@return the filter
@mongodb.driver.manual reference/operator/query/nor $nor

Creates a filter that performs a logical NOR operation on all the specified filters .


public static Bson exists(final String fieldName, final boolean exists) {
        return new OperatorFilter<BsonBoolean>("$exists", fieldName, BsonBoolean.valueOf(exists));
    }

public static Bson exists ( final String fieldName , final boolean exists ) { return new OperatorFilter < BsonBoolean > ( "$exists" , fieldName , BsonBoolean . valueOf ( exists ) ) ; }

Creates a filter that matches all documents that either contain or do not contain the given field, depending on the value of the
exists parameter.

@param fieldName the field name
@param exists    true to check for existence, false to check for absence
@return the filter
@mongodb.driver.manual reference/operator/query/exists $exists

Creates a filter that matches all documents that either contain or do not contain the given field depending on the value of the exists parameter .


@Deprecated
    public static Bson text(final String search, final String language) {
        notNull("search", search);
        return text(search, new TextSearchOptions().language(language));
    }

@ Deprecated public static Bson text ( final String search , final String language ) { notNull ( "search" , search ) ; return text ( search , new TextSearchOptions ( ) . language ( language ) ) ; }

Creates a filter that matches all documents matching the given search term using the given language.

@param search   the search term
@param language the language to use for stop words
@return the filter
@mongodb.driver.manual reference/operator/query/text $text
@deprecated use {@link Filters#text(String, TextSearchOptions)}

Creates a filter that matches all documents matching the given search term using the given language .


public static Bson text(final String search, final TextSearchOptions textSearchOptions) {
        notNull("search", search);
        notNull("textSearchOptions", textSearchOptions);
        return new TextFilter(search, textSearchOptions);
    }

public static Bson text ( final String search , final TextSearchOptions textSearchOptions ) { notNull ( "search" , search ) ; notNull ( "textSearchOptions" , textSearchOptions ) ; return new TextFilter ( search , textSearchOptions ) ; }

Creates a filter that matches all documents matching the given the search term with the given text search options.

@param search            the search term
@param textSearchOptions the text search options to use
@return the filter
@mongodb.driver.manual reference/operator/query/text $text
@since 3.2

Creates a filter that matches all documents matching the given the search term with the given text search options .


public static Bson elemMatch(final String fieldName, final Bson filter) {
        return new Bson() {
            @Override
            public <TDocument> BsonDocument toBsonDocument(final Class<TDocument> documentClass, final CodecRegistry codecRegistry) {
                return new BsonDocument(fieldName, new BsonDocument("$elemMatch", filter.toBsonDocument(documentClass, codecRegistry)));
            }
        };
    }

public static Bson elemMatch ( final String fieldName , final Bson filter ) { return new Bson ( ) { @ Override public < TDocument > BsonDocument toBsonDocument ( final Class < TDocument > documentClass , final CodecRegistry codecRegistry ) { return new BsonDocument ( fieldName , new BsonDocument ( "$elemMatch" , filter . toBsonDocument ( documentClass , codecRegistry ) ) ) ; } } ; }

Creates a filter that matches all documents containing a field that is an array where at least one member of the array matches the
given filter.

@param fieldName the field name
@param filter    the filter to apply to each element
@return the filter
@mongodb.driver.manual reference/operator/query/elemMatch $elemMatch

Creates a filter that matches all documents containing a field that is an array where at least one member of the array matches the given filter .


public static Bson geoWithinBox(final String fieldName, final double lowerLeftX, final double lowerLeftY, final double upperRightX,
                                    final double upperRightY) {
        BsonDocument box = new BsonDocument("$box",
                                                   new BsonArray(asList(new BsonArray(asList(new BsonDouble(lowerLeftX),
                                                           new BsonDouble(lowerLeftY))),
                                                           new BsonArray(asList(new BsonDouble(upperRightX),
                                                                   new BsonDouble(upperRightY))))));
        return new OperatorFilter<BsonDocument>("$geoWithin", fieldName, box);
    }

public static Bson geoWithinBox ( final String fieldName , final double lowerLeftX , final double lowerLeftY , final double upperRightX , final double upperRightY ) { BsonDocument box = new BsonDocument ( "$box" , new BsonArray ( asList ( new BsonArray ( asList ( new BsonDouble ( lowerLeftX ) , new BsonDouble ( lowerLeftY ) ) ) , new BsonArray ( asList ( new BsonDouble ( upperRightX ) , new BsonDouble ( upperRightY ) ) ) ) ) ) ; return new OperatorFilter < BsonDocument > ( "$geoWithin" , fieldName , box ) ; }

Creates a filter that matches all documents containing a field with grid coordinates data that exist entirely within the specified
box.

@param fieldName   the field name
@param lowerLeftX  the lower left x coordinate of the box
@param lowerLeftY  the lower left y coordinate of the box
@param upperRightX the upper left x coordinate of the box
@param upperRightY the upper left y coordinate of the box
@return the filter
@mongodb.driver.manual reference/operator/query/geoWithin/ $geoWithin
@mongodb.driver.manual reference/operator/query/box/#op._S_box $box
@mongodb.server.release 2.4
@since 3.1

Creates a filter that matches all documents containing a field with grid coordinates data that exist entirely within the specified box .


public static Bson geoWithinPolygon(final String fieldName, final List<List<Double>> points) {
        BsonArray pointsArray = new BsonArray();
        for (List<Double> point : points) {
            pointsArray.add(new BsonArray(asList(new BsonDouble(point.get(0)), new BsonDouble(point.get(1)))));
        }
        BsonDocument polygon = new BsonDocument("$polygon", pointsArray);
        return new OperatorFilter<BsonDocument>("$geoWithin", fieldName, polygon);
    }

public static Bson geoWithinPolygon ( final String fieldName , final List < List < Double > > points ) { BsonArray pointsArray = new BsonArray ( ) ; for ( List < Double > point : points ) { pointsArray . add ( new BsonArray ( asList ( new BsonDouble ( point . get ( 0 ) ) , new BsonDouble ( point . get ( 1 ) ) ) ) ) ; } BsonDocument polygon = new BsonDocument ( "$polygon" , pointsArray ) ; return new OperatorFilter < BsonDocument > ( "$geoWithin" , fieldName , polygon ) ; }

Creates a filter that matches all documents containing a field with grid coordinates data that exist entirely within the specified
polygon.

@param fieldName the field name
@param points    a list of pairs of x, y coordinates.  Any extra dimensions are ignored
@return the filter
@mongodb.driver.manual reference/operator/query/geoWithin/ $geoWithin
@mongodb.driver.manual reference/operator/query/polygon/#op._S_polygon $polygon
@mongodb.server.release 2.4
@since 3.1

Creates a filter that matches all documents containing a field with grid coordinates data that exist entirely within the specified polygon .