Search code examples
node.jsmongodbsynchronizationreplicationmean-stack

How to automatically choose mongodb based on location?


I'm creating a MEAN web project as my hobby. I have two mongoDB, one is in Japan and another one is in China. Can I configure my application to use different mongoDB based on location? For example, if the user is accessing from China, then the application should be able to choose mongoDB located in China. Is there any way to do this?


Solution

  • This can be achieved using tag based sharding or tag aware sharding. Basically, it works like this:

    1. You have a value in your documents which denotes wether this specific document belongs to your chinese or your japanese data set, eg. location: 'CHN' or location: 'JPN'
    2. You set up a sharded cluster, where one shard is in a datacenter in China and the other resides in Japan.
    3. You assign tags to each shard. In your case it would make sense to tag the Chinese shard with CHN and the Japanese shard with JPN
    4. Now you can configure the shards that the Japanese shard should hold all documents with location: 'JPN' and the Chinese shard to hold all documents to hold all documents with the location: CHN with assigning those values to the accordingly tagged shards:

      sh.addTagRange("database.collcetion", { location: "CHN" }, { location: "CHN" }, "CHN") sh.addTagRange("database.collcetion", { location: "JPN" }, { location: "JPN" }, "JPN")

    5. Use location as your shard key.

    6. Now, you can use a single database and the data will be automatically geographically distributed and your application's queries will always be routed to the geographically matching data center.