Mongodb – Can we replicate or restrict specific databases in MongoDB


In MySQL, we are having replicate-do-db/replicate-ignore-db during replication, where we can replicate or restrict specific databases from Master to Slave.

In the similar way, is there any specific configuration or work around in MongoDB replication to restrict specific databases and collections during data sync.

If not, is there any other way to sync only specific database or collections from Master to Slave.

I am using MongoDB 3.6

Best Answer

Replica sets in MongoDB are designed for data redundancy and failover, so all data-bearing members of a replica set currently contain the same databases & collections as at MongoDB 4.2. A member with a partial data set would not be able to fulfil either of these key design goals for a replica set deployment.

There is a relevant server issue you can watch & upvote: SERVER-1559: Ability for a replica set node to only have a subset of the databases or collections. This is currently on the development backlog but there is an alternative approach you can use in the interim.

If you want to support non-standard replication/sync scenarios, I would look into writing a small program to replicate desired changes using the MongoDB Change Streams API. Change stream events are based on the replication oplog and allow you to filter and process relevant events matching on criteria such as namespace, operation type, or field values. You can also modify change stream output using additional aggregation stages (for example, projecting a subset of fields or adding calculated fields). Most importantly, the Change Streams API gives you a supported upgrade path to future versions of the MongoDB server.

In MongoDB 3.6 you can only open change streams at a collection level. Since you are interested in changes at a database or deployment level, it would be worth upgrading to MongoDB 4.0 which includes more comprehensive change stream support.