Master Master Replication

Mongo does not support full master-master replication.  However, for certain restricted use cases master-master can be used.  Generally speaking, we don't recommend the using a master-master configuration with MongoDB.

Master-master usages is eventually consistent.

To configure master-master, simply run both databases with both the --master and --slave parameters.  For example, to set up this configuration on a single machine as a test one might run:

$ nohup mongod --dbpath /data1/db --port 27017 --master --slave --source localhost:27018 > /tmp/dblog1 &
$ nohup mongod --dbpath /data2/db --port 27018 --master --slave --source localhost:27017 > /tmp/dblog2 &

This mode is safe for:

  • insert operations
  • delete operations by _id;
  • any query

Master-master should not be used if:

  • concurrent updates of single object may occur (including $inc and other updates)

A sample test session on a single computer follows:

$ # terminal 1, we run a mongod on default db port (27017)
$ ./mongod --slave --master --source localhost:10000

$ # terminal 2, we run a mongod on port 10000
$ ./mongod --slave --master --dbpath /data/slave --port 10000 --source localhost

$ # terminal 3, we run the shell here
$ ./mongo
> // 'db' is now connected to localhost:27017/test
> z = connect("localhost:10000/test")
> // 'z' is now connected to localhost:10000/test db

> db.foo.insert({x:7});
> z.foo.find()
{"_id" :  ObjectId( "4ab917d7c50e4c10591ce3b6")  , "x" : 7}
> db.foo.find()
{"_id" :  ObjectId( "4ab917d7c50e4c10591ce3b6")  , "x" : 7}

> db.foo.insert({x:8})
> db.foo.find()
{"_id" :  ObjectId( "4ab917d7c50e4c10591ce3b6")  , "x" : 7}
{"_id" :  ObjectId( "4ab9182a938798896fd8a906")  , "x" : 8}
> z.foo.find()
{"_id" :  ObjectId( "4ab917d7c50e4c10591ce3b6")  , "x" : 7}
{"_id" :  ObjectId( "4ab9182a938798896fd8a906")  , "x" : 8}

> z.foo.save({x:9})
> z.foo.find()
{"_id" :  ObjectId( "4ab917d7c50e4c10591ce3b6")  , "x" : 7}
{"_id" :  ObjectId( "4ab9182a938798896fd8a906")  , "x" : 8}
{"_id" :  ObjectId( "4ab9188ac50e4c10591ce3b7")  , "x" : 9}
> db.foo.find()
{"_id" :  ObjectId( "4ab917d7c50e4c10591ce3b6")  , "x" : 7}
{"_id" :  ObjectId( "4ab9182a938798896fd8a906")  , "x" : 8}
{"_id" :  ObjectId( "4ab9188ac50e4c10591ce3b7")  , "x" : 9}

> z.foo.remove({x:8})
> db.foo.find()
{"_id" :  ObjectId( "4ab917d7c50e4c10591ce3b6")  , "x" : 7}
{"_id" :  ObjectId( "4ab9188ac50e4c10591ce3b7")  , "x" : 9}
> z.foo.find()
{"_id" :  ObjectId( "4ab917d7c50e4c10591ce3b6")  , "x" : 7}
{"_id" :  ObjectId( "4ab9188ac50e4c10591ce3b7")  , "x" : 9}

> db.foo.drop()
{"nIndexesWas" : 1 , "msg" : "all indexes deleted for collection" , "ns" : "test.foo" , "ok" : 1}
> db.foo.find()
> z.foo.find()
>


Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

PLEASE POST QUESTIONS IN THE USER GROUPS FORUM. Post non-question comments and helpful hints here.

blog comments powered by Disqus