Hi Stone
one of my user move from regionA to regionB.It would cause high latency while need to write data to local datacenter in regionA.
This seems to me a use case for sharding, particularly tag aware sharding. You may put one shard (or more) in each data center and ensure that all regionA users belong to the shard(s) in regionA data center, all regionB users belong to regionB shard(s).
Let’s assume we have two data centers, each of which correspond to a region. The following example shows how to write using a tag aware sharding:
Set up a two-shard cluster: “shard01” and “shard02”
Tag those two shards
sh.addShardTag('shard01', 'regionA');
sh.addShardTag('shard02', 'regionB');
Shard collection “users” in database “demo”
sh.enableSharding('demo');
sh.shardCollection('demo.users', {home_location:1, user_id: 1});
Attach home location to corresponding shard tags
sh.addTagRange('demo.users',
{home_location:'regionA', user_id:MinKey},
{home_location:'regionA', user_id:MaxKey},
'regionA');
sh.addTagRange('demo.users',
{home_location:'regionB', user_id:MinKey},
{home_location:'regionB', user_id:MaxKey},
'regionB');
Insert documents of different regions
db.users.insert({home_location:'regionA', user_id:1, name:'adam'});
db.users.insert({home_location:'regionB', user_id:2, name:'bob'});
Verify that documents are stored in shards as expected using either way:
Run the following commands and check output.
sh.status();
db.users.find({user_id:1}).explain({verbose:1});
db.users.find({user_id:2}).explain({verbose:1});
Or, connect to and query on each shard directly.
NOTE: If there is already some data before sharding/tagging, we may need to wait for some time to allow chunks migrate to designated shards respectively.
Move one user to another region
Since values of shard keys cannot be changed, we have to delete the user and re-insert it with new location info.
var adam = db.users.findOneAndDelete({home_location:'regionA', user_id:1});
adam.home_location = 'regionB';
db.users.insert(adam);
Make sure you perform tests under your specific environment and use cases first, before making changes to your production systems. Refer to Manage Shard Tags and Segmenting Data by Location for more information.
Regards,
Lungang