Always connect & query against the Primary in ReplicaSet

39 views
Skip to first unread message

Richard Seldon

unread,
Jan 18, 2017, 8:46:41 AM1/18/17
to mongodb-user

Hello, 

Have a requirement to always connect & query (find / delete operations) against the PRIMARY MongoDB in a replica set.

Was looking at this StackOverflow answer for how to do this from the Command Line :  http://stackoverflow.com/a/28120454/1882064

```
db.runCommand("ismaster")
{
     "ismaster" : false,
     "secondary" : true,
     "hosts" : [
             "ny1.acme.com",
             "ny2.acme.com",
             "sf1.acme.com"
     ],
     "passives" : [
          "ny3.acme.com",
          "sf3.acme.com"
     ],
     "arbiters" : [
         "sf2.acme.com",
     ]
     "primary" : "ny2.acme.com",
     "ok" : true
}
```

Above, actually to do the opposite, and always connect to a Secondary MongoDB in a replica set.

How can I achieve the same using the Node Mongo DB Driver - is it just a case of adding the above as options to the Connection ?


```
const options = {  // complete here... };

MongoClient.connect(config.MONGO_URL, options, (err, db) => {
```

Any details / docs / code snippets most welcome. Thank you.


Wan Bachtiar

unread,
Jan 26, 2017, 8:22:50 PM1/26/17
to mongodb-user

Have a requirement to always connect & query (find / delete operations) against the PRIMARY MongoDB in a replica set.

Hi Richard,

The isMaster() command is normally used to find out whether or not an instance is the primary of the replica set. Not to set a client to read from the primary of a replica set.

The connection preference to perform queries (i.e. find() ) can be configured by setting Read Preference. However, write/update operations (i.e. deleteOne()), can only be performed on the replica set primary member. Also see Replication for more information.

How can I achieve the same using the Node Mongo DB Driver - is it just a case of adding the above as options to the Connection ?

See MongoDB Node.JS Driver: Connect to a Replica Set for code example and information. Note that the default read preference value of the driver is to read from primary.

You may find the following resources useful:

If you have further questions, could you provide the following:

  • MongoDB version.
  • MongoDB Node.JS driver version.
  • Snippet code of how you’re making the connection, along with the options.
  • The MongoDB connection string URI that you’re using.
  • What led you to believe that you’re not connecting to the primary from your application?

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages