Skip to content

Instantly share code, notes, and snippets.

@crshmk
Last active December 18, 2024 10:09
Show Gist options
  • Save crshmk/51319566398efd1fe0bd61ef589cc5e8 to your computer and use it in GitHub Desktop.
Save crshmk/51319566398efd1fe0bd61ef589cc5e8 to your computer and use it in GitHub Desktop.
Local MongoDb replication

1. Set up replicas

Local Mongo replication

Find mongod.conf

mongosh 

db.serverCmdLineOpts()

Edit mongod.conf

replication:
   oplogSizeMB: <int>
   replSetName: <string>
   enableMajorityReadConcern: true

restart

brew services stop / start mongodb-community

sytemctl restart mongod 

service mongod restart

systemctl restart mongod

# etc

Open mongosh and initiate the replica set

mongosh
# go straight to the local db
use local
# initiate the replica sets
rs.initiate()

# now you can use whateverDb

# use todos
# $ replicaSetName [direct: primary] todos>

2. Test the reactivity

with the Mongo driver's ChangeStream wrapping Node's EventEmitter

  • Init a package and install mongodb
  • Run this script
  • Insert an item into the collection
  • Notice the logs
const { MongoClient } = require('mongodb')

// replicaSet= the name you used above in the config for replication.replSetName
const client = new MongoClient("mongodb://localhost:27017/?replicaSet=yourSet")

const react = async () => {
  await client.connect()

  const pipeline = [
    {
      '$match': {
        'operationType': 'insert'
      }
    }
  ]
  
  const collection = client.db("dbName").collection("collectionName")
  
  const changeStream = collection.watch(pipeline)
  
  changeStream.on('change', (next) => {
    console.log(next)
  })
}

react()

e.g.

{
  _id: {
    _data: '8262629A02000000012B082C0105296E5A10049405576EFADE42D0919B3DF337E90AAC463C6F7065726174696F6E54797065003C696E736572740046646F63756D656E744B65790046645F6964006467629A02526DE4387C4820DF000009'
  },
  operationType: 'insert',
  clusterTime: new Timestamp({ t: 1734515202, i: 1 }),
  wallTime: 2024-12-18T09:46:42.671Z,
  fullDocument: {
    _id: new ObjectId('67629a02526de4387c4820df'),
    items: [ [Object], [Object] ],
    createdAt: 2024-12-18T09:46:42.669Z,
    updatedAt: 2024-12-18T09:46:42.669Z,
    __v: 0
  },
  ns: { db: 'food', coll: 'orders' },
  documentKey: { _id: new ObjectId('67629a02526de4387c4820df') }
}

Docs

ChangeStreams

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment