Dev
Dev

Reputation: 13753

How to use MongoClientOptions instead of MongoOptions?

I am using MongoOptions class and its methods

setFsync(boolean sync)

setJ(boolean safe)

setW(int val)

setWtimeout(int timeoutMS)

setSafe(boolean isSafe)

How to achieve this using MongoClientOptions as MongoOptions is depracated in Mongo-Java-Driver 3.0. I came to know MongoClientOptions uses

MongoClientOptions.builder()

to create a new Builder instance and then append properties.

Upvotes: 7

Views: 10869

Answers (3)

Jose Quinteiro
Jose Quinteiro

Reputation: 489

Things are quite a bit more complicated with client version 3.6. You'll have to instantiate a WriteConcern and use it with MongoClientOptions.Builder. Example:

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.mongodb.WriteConcernError;

public class MongoOptionsSample
{
    public static void main( String[] args )
    {
        WriteConcern l_concern = new WriteConcern( wVal, wTimeoutMS )
                .withJournal( bool );

        MongoClientOptions l_opts =
                MongoClientOptions
                .builder()
                .writeConcern( l_concern )
                .build();

        ServerAddress l_addr = new ServerAddress( "localhost", 27017 );

        try
        (
                MongoClient l_conn = new MongoClient( l_addr, l_opts );
        )
        {
            ...
        }
    }
}

Fsync and safe are deprecated. See the WriteConcern documentation for details.

Upvotes: 2

Aman
Aman

Reputation: 3261

You can use like below:You can set the read prefernece and write concern using object of new Mongoclient...There are list of apis are available .Please check the below format..

        MongoClient c =  new MongoClient(new MongoClientURI("mongodb://localhost"));
        DB db = c.getDB("final");
        DBCollection animals = db.getCollection("emp");


        BasicDBObject animal = new BasicDBObject("emp", "john");
MongoClientOptions options = new MongoClient().setReadPreference(preference);
MongoClientOptions options = new MongoClient().setWriteConcern(concern);  

You can add fsynk aswell..

MongoClientOptions options = new MongoClient().fsync(async)

Upvotes: 1

jyemin
jyemin

Reputation: 3813

Use the writeConcern method on the builder, as in:

MongoClientOptions options = MongoClientOptions.builder()
                                               .writeConcern(WriteConcern.JOURNALED)
                                               .build();

or

Upvotes: 4

Related Questions