Mongodb Watch for Sharded DB

Hi ,

I was trying to connect with Sharded DB with Java watch for listening to insert operations, but i was unable to connect to db getting the following error(The $changeStream stage is only supported on replica sets). But in the Mongodb documentation it is said it will work for replica and also sharded(mongos instance) .
Please suggest me how to work with this sharded db watch().

Hey @gopinath_pappu,

Welcome to the MongoDB University forums :sparkles:

You need to make your Mongo database a replica set with one node only in order to read the oplog!

So you need to start your mongod with the --replSet option or edit the mongod.conf to include a replication section. i.e:

replication:
  replSetName: my-replica-set

Then start or restart the server with these changes, and then connect with the mongo shell and enter:

rs.initiate()

Now you can write code that relies on an Oplog to be present.

For more info please refer to the official documentation: Convert a Standalone to a Replica Set

In case you have any doubts, please feel free to reach out to us!

Thanks,
Kushagra

Hi @Kushagra_Kesav,

Thanks for your reply, but when i went through the Mongodb manual it is stated that watch will work for both Replica and Sharded Clusters (For replica sets and sharded clusters only). Please check this link for reference (https://docs.mongodb.com/manual/reference/method/db.collection.watch/).

Hi @gopinath_pappu,

Yes, it is written in the documentation but it will only work if you have at least single-member replica sets for the shards! Can you confirm that the shards in their replica set are standalone instances or replica sets?

If it is a sharded cluster of standalone instances then it will not work. You’d need to have at least single-member replica sets for the shards!

Thanks,
Kushagra