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?
This can be achieved using tag based sharding or tag aware sharding. Basically, it works like this:
location: 'CHN' or location: 'JPN'CHN and the Japanese shard with JPNNow 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")
Use location as your shard key.
Could you post the part of your code where you are sending the data to MongoDB, since you should have opened two connection.
Open two connection, one will be MongoChina, the other MongoJapan.
When a user connect, get his ip adress, and choose where which connection use based on this.
Pseudo code:
var MongoChina = //Connecting to the chinese mongo server,
MongoJapan = //Connecting to the japanese mongo server;
function isJapanese(ip) {
//Return true if IP is in japanese ip range
//http://www.nirsoft.net/countryip/jp.html
}
function isChinese(ip) {
//Return true if IP is in chinese ip range
//http://www.nirsoft.net/countryip/cn.html
}
on.('user_connecting', function (req, res) {
var ip = //Extract the user ip from the request;
if (isJapanese(ip)) {
getDataToSendToMongo(function (data) {
MongoJapan.send(data);
});
} else if (isChinese(ip)) {
getDataToSendToMongo(function (data) {
MongoChina.send(data);
});
} else {
//Do whatever you like
}
});