When you need to connect to a MongoDB database on another machine within your local network, follow these steps:
Step 1: Ensure MongoDB is installed and running on the target machine
First, confirm that MongoDB is installed and running on the target machine. You can check the status of the MongoDB service using the following command:
bashsudo systemctl status mongod
If the service is not running, use the following command to start it:
bashsudo systemctl start mongod
Step 2: Configure MongoDB to allow remote connections
By default, MongoDB does not allow remote connections. You need to modify its configuration file mongod.conf, typically found at /etc/mongod.conf.
Find the net section and ensure it is configured as follows:
yamlnet: port: 27017 bindIp: 0.0.0.0
Here, bindIp: 0.0.0.0 means that any IP address can connect. For security reasons, you can also set it to a specific IP address range within your local network.
After modifying the configuration, restart the MongoDB service:
bashsudo systemctl restart mongod
Step 3: Configure the firewall (if applicable)
Ensure that the firewall rules on the target machine permit access to the MongoDB port (default: 27017) from your IP address. For example, if you are using the ufw firewall, you can run:
bashsudo ufw allow from your IP address to any port 27017
Step 4: Connect to MongoDB from your machine
Now, you can use the MongoDB client tools to connect to the MongoDB database on the target machine from your machine. For example, using the mongo command-line client, you can do the following:
bashmongo --host target machine's IP address --port 27017
If you need a username and password, add the -u (username) and -p (password) parameters.
Example
For example, if the target machine's IP address is 192.168.1.5, the username is admin, and the password is password, you can use the following command to connect:
bashmongo --host 192.168.1.5 --port 27017 -u admin -p password
Following these steps, you should be able to successfully connect to the MongoDB database on another machine within your local network.