Windows install Mongo, single machine open replication set

Time:2020-12-4

Install Mongo:

1. To download Mongo, do not check the user-defined path and install mongodb compass (this is the graphical interface in the figure below, which can’t be moved at all). For other default configurations, you can use the next route.
2. Configuration environment variable: D: program files mongodbserver4.4bin
3. Create two directories, data and log, in Bin of the installation directory mongo.config And create a file in the log mongo.log
4. Create a file in the bin directory at the same level: mongo.config [in fact, the location of this file can also be changed, just specify it in the startup command]
mongo.confi The contents are as follows: replset = RS, and the specified replica set is rs
Note that if you want the Internet to be able to connect to Mongo, you need to specify bind_ IP is 0.0.0.0;

dbpath = D:\Program Files\MongoDB\Server.4\data\db
logpath = D:\Program Files\MongoDB\Server.4\data\log\mongo.log
port=27017
journal=true
replSet=rs

5. Start Mongo service in config mode

mongod --config "D:\Program Files\MongoDB\Server.4\mongo.config"

6. Log in to Mongo:
Because there is no login password set here, you can log in directly

mongo -port 27017

7. Perform initialization:
Enter the local library and execute initialization

use local
rs.initiate({ _id: "rs", members: [{_id:0,host:"127.0.0.1:27017"}]})

At this time:
You can see that RS: secondary > is changed to Rs: primary >, indicating that the configuration is successful
Windows install Mongo, single machine open replication set

2、 Java uses changestream single node to monitor database

[Mongo 3.6 and above only]
Build DB: Test and collection: mytest in Mongo
Maven relies on:

<dependency>
 <groupId>org.mongodb</groupId>
 <artifactId>mongodb-driver</artifactId>
 <version>3.11.2</version>
</dependency>

Java listening Code:~~~~

public static void main(String[] args) {
 MongoClient mongoClient = MongoClients.create("mongodb://localhost");
    MongoDatabase mDatabase = mongoClient.getDatabase("test");
    MongoCollection<Document> collection = mDatabase.getCollection("myTest");

 MongoCursor<ChangeStreamDocument<Document>> cursor = collection.watch().fullDocument(FullDocument.UPDATE_LOOKUP).iterator();
    while (cursor.hasNext()){
 ChangeStreamDocument<Document> next = cursor.next();
            String s = next.getFullDocument().toJson();
            System.out.println(s);
    }
}