简体   繁体   中英

Jongo MongoDB: How to specify a default ReadPreference

I am aware that I can set the readPreference for each query using <collection>.withReadPreference(primaryPreferred()).find(...) . However, I would prefer to set a global default readPreference to use "nearest" if possible, and then be able to override this for individual queries if necessary. Is there a possible/preferred way to do this using Jongo?

Edit: Since Jongo is initialized using MongoClient().getDB() , would it therefor be suitable to initialize my MongoClient with options specifying the ReadPreference? I guess what I'm asking is - if I do it this way, will these settings carry over and be applied inside of Jongo, or is there a different way to handle it in Jongo directly?

Thanks ahead of time.

Probably should have just tried it before asking, but I will provide an answer for anyone who may have this question in the future. The short answer is - Yes, setting it via the MongoClient using the MongoClientOptions object will carry over to Jongo.

Specifically, I had something like this in a method to build the options (made it more verbose than I had to for clarity for this example):

protected MongoClientOptions getOptions(){
    MongoClientOptions mClientOpts;
    Builder mClientOptionsBuilder = new MongoClientOptions.Builder();
    mClientOptionsBuilder.readPreference(ReadPreference.nearest());
    mClientOpts = mClientOptionsBuilder.build(); 
    System.out.println("[MongoConfig]: " + mClientOpts.toString());

    return mClientOpts;
}

Then you can just instantiate a new MongoClient(new ServerAddress(...), this.getOptions()); and use that client instance to get your database reference which is finally used as an argument to instantiate Jongo.

To be clear, the reason I was doing this was to be able to read from Secondary members of a MongoDB ReplicaSet if/when those were available with the lowest latency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM