局网设置mongodb服务的方法。

ubuntu

建议安装最新的稳定版本的 MongoDB,以确保获得最新的功能和安全更新。你可以按照以下步骤在 Ubuntu 服务器上安装 MongoDB:

  1. 导入 MongoDB 公共 GPG 密钥:

```bash

wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -

```

  1. 创建一个 MongoDB 的源列表文件:

```bash

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list

```

  1. 更新本地包数据库:

```bash

sudo apt-get update

```

  1. 安装 MongoDB:

```bash

sudo apt-get install -y mongodb-org

```

  1. 启动 MongoDB 服务并设置为开机自启动:

```bash

sudo systemctl start mongod

sudo systemctl enable mongod

```

  1. 检查 MongoDB 服务状态:

```bash

sudo systemctl status mongod

```

这样,你就可以在服务器上安装并运行 MongoDB 服务了。

win

建议安装最新的稳定版本的 MongoDB,以确保获得最新的功能和安全更新。以下是在 Windows 系统上安装 MongoDB 的步骤:

  1. **下载 MongoDB 安装程序**:

从 [MongoDB 官方下载页面](https://www.mongodb.com/try/download/community) 下载最新的 MongoDB Community Server 安装程序。

  1. **运行安装程序**:

双击下载的安装程序,按照提示进行安装。建议选择"Complete"安装类型。

  1. **配置 MongoDB**:

安装完成后,MongoDB 默认会安装在 `C:\Program Files\MongoDB\Server\<version>\` 目录下。你可以在 `C:\Program Files\MongoDB\Server\<version>\bin` 目录下找到 `mongod.exe` 和 `mongo.exe` 文件。

  1. **创建数据目录**:

MongoDB 需要一个数据目录来存储数据。默认情况下,它会使用 `C:\data\db` 目录。你可以手动创建这个目录:

```batch

mkdir C:\data\db

```

  1. **启动 MongoDB 服务**:

打开命令提示符,运行以下命令启动 MongoDB 服务:

```batch

"C:\Program Files\MongoDB\Server\<version>\bin\mongod.exe" --dbpath="C:\data\db"

```

  1. **设置 MongoDB 为 Windows 服务**(可选):

你可以将 MongoDB 设置为 Windows 服务,以便在系统启动时自动运行。运行以下命令:

```batch

"C:\Program Files\MongoDB\Server\<version>\bin\mongod.exe" --config "C:\Program Files\MongoDB\Server\<version>\bin\mongod.cfg" --install

```

  1. **验证安装**:

打开另一个命令提示符窗口,运行以下命令连接到 MongoDB 实例:

```batch

"C:\Program Files\MongoDB\Server\<version>\bin\mongo.exe"

```

这样,你就可以在 Windows 系统上安装并运行 MongoDB 服务了。

要让其他机器通过IP和端口访问MongoDB数据库,你需要进行以下配置:

  1. **修改MongoDB配置文件**:

打开MongoDB的配置文件`mongod.conf`,找到`bindIp`设置,将其修改为`0.0.0.0`,以允许所有IP地址访问。

```yaml

net:

port: 27017

bindIp: 0.0.0.0

```

  1. **重启MongoDB服务**:

修改配置文件后,重启MongoDB服务以使更改生效。

```bash

sudo systemctl restart mongod

```

  1. **配置防火墙**:

确保防火墙允许MongoDB的默认端口(27017)通过。你可以使用以下命令来允许端口27017通过防火墙:

```bash

sudo ufw allow 27017

```

  1. **设置用户认证(可选)**:

为了安全起见,建议设置用户认证。你可以在MongoDB shell中创建一个管理员用户:

```javascript

use admin

db.createUser({

user: "admin",

pwd: "password",

roles: [{ role: "userAdminAnyDatabase", db: "admin" }]

})

```

完成以上步骤后,其他机器就可以通过`<服务器IP>:27017`的方式访问你的MongoDB数据库了。

win安装测试:

1.下载地址:

Download MongoDB Community Server | MongoDB

2.一路下一步。

在 Windows 下,你可以使用以下步骤重启 MongoDB 服务并将其设置为开机自启动:

  1. **重启 MongoDB 服务**:

打开命令提示符(以管理员身份运行),然后运行以下命令来重启 MongoDB 服务:

```batch

net stop MongoDB

net start MongoDB

```

The error you are encountering is because the `sc` command is not recognized in PowerShell. Instead, you should use the `Set-Service` cmdlet in PowerShell to configure the MongoDB service to start automatically.

Here is the correct command to set the MongoDB service to start automatically:

```powershell

Set-Service -Name "MongoDB" -StartupType Automatic

```

To restart the MongoDB service, you can use the following command:

```powershell

Restart-Service -Name "MongoDB"

```

These commands should be run in an elevated PowerShell window (Run as Administrator).

测试连接

要连接并测试 MongoDB 服务,可以按照以下步骤进行:

  1. **安装 MongoDB 客户端**:

确保你已经安装了 MongoDB 客户端工具 `mongo`。如果没有安装,可以从 [MongoDB 官方下载页面](https://www.mongodb.com/try/download/community) 下载并安装。

  1. **连接到 MongoDB**:

打开命令提示符或 PowerShell,运行以下命令连接到 MongoDB 服务:

```powershell

mongo --host <服务器IP> --port 27017

```

将 `<服务器IP>` 替换为你的 MongoDB 服务器的 IP 地址。

  1. **测试连接**:

连接成功后,你会进入 MongoDB shell。你可以运行以下命令来测试连接:

```javascript

use test

db.testCollection.insertOne({ name: "test", value: 1 })

db.testCollection.find()

```

这将创建一个名为 `test` 的数据库,并在其中插入一个文档,然后查询该文档以验证插入是否成功。

通过以上步骤,你可以连接并测试 MongoDB 服务。

测试

python 测试

pip install pymongo

from pymongo import MongoClient

# Replace with your MongoDB server IP and port
mongo_host = "10.73.30.169"
mongo_port = 27017

# Create a MongoClient to the running mongod instance
client = MongoClient(mongo_host, mongo_port)

# Test the connection by listing the databases
try:
    databases = client.list_database_names()
    print("Connected to MongoDB server successfully.")
    print("Databases:", databases)
except Exception as e:
    print("Failed to connect to MongoDB server.")
    print("Error:", e)

更多安全设置:

要为 MongoDB 设置用户名和密码以确保安全性,可以按照以下步骤进行:

  1. **启动 MongoDB**:

确保 MongoDB 服务正在运行。

  1. **连接到 MongoDB**:

使用 MongoDB shell 连接到 MongoDB 实例:

```bash

mongo

```

  1. **创建管理员用户**:

切换到 `admin` 数据库并创建管理员用户:

```javascript

use admin

db.createUser({

user: "admin",

pwd: "password",

roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]

})

```

  1. **启用身份验证**:

编辑 MongoDB 配置文件(通常位于 `C:\Program Files\MongoDB\Server\<version>\bin\mongod.cfg`)并添加以下行:

```yaml

security:

authorization: enabled

```

然后重启 MongoDB 服务:

```bash

net stop MongoDB

net start MongoDB

```

  1. **创建应用用户**:

以管理员身份重新连接到 MongoDB 并创建应用用户:

```bash

mongo -u "admin" -p "password" --authenticationDatabase "admin"

```

然后在目标数据库中创建用户:

```javascript

use yourDatabase

db.createUser({

user: "appUser",

pwd: "appPassword",

roles: [ { role: "readWrite", db: "yourDatabase" } ]

})

```

  1. **使用用户名和密码连接 MongoDB**:

在应用程序中使用用户名和密码连接到 MongoDB,例如在 Python 中:

```python

from pymongo import MongoClient

Replace with your MongoDB server IP, port, username, and password

mongo_host = "10.73.30.169"

mongo_port = 27017

username = "appUser"

password = "appPassword"

Create a MongoClient to the running mongod instance with authentication

client = MongoClient(f"mongodb://{username}:{password}@{mongo_host}:{mongo_port}/?authSource=yourDatabase")

Test the connection by listing the databases

try:

databases = client.list_database_names()

print("Connected to MongoDB server successfully.")

print("Databases:", databases)

except Exception as e:

print("Failed to connect to MongoDB server.")

print("Error:", e)

```

通过这些步骤,你可以为 MongoDB 设置用户名和密码,并确保连接时使用身份验证。

from pymongo import MongoClient

# Replace with your MongoDB server IP, port, username, and password
mongo_host = "10.73.30.169"
mongo_port = 27017
username = "appUser"
password = "appPassword"

# Create a MongoClient to the running mongod instance with authentication
client = MongoClient(f"mongodb://{username}:{password}@{mongo_host}:{mongo_port}/?authSource=yourDatabase")

# Test the connection by listing the databases
try:
    databases = client.list_database_names()
    print("Connected to MongoDB server successfully.")
    print("Databases:", databases)
except Exception as e:
    print("Failed to connect to MongoDB server.")
    print("Error:", e)

from pymongo import MongoClient

# Replace with your MongoDB server IP and port
mongo_host = "10.73.30.169"
mongo_port = 27017

# Create a MongoClient to the running mongod instance
client = MongoClient(mongo_host, mongo_port)

# Test the connection by listing the databases
try:
    databases = client.list_database_names()
    print("Connected to MongoDB server successfully.")
    print("Databases:", databases)
    client.close()
except Exception as e:
    print("Failed to connect to MongoDB server.")
    print("Error:", e)

# Create a MongoClient to the running mongod instance
client = MongoClient(mongo_host, mongo_port)

# Test the connection by listing the databases
try:
    databases = client.list_database_names()
    print("Connected to MongoDB server successfully.")
    print("Databases:", databases)

    # Create a new database named 'test'
    db = client['test']
    # Optionally, create a collection in the 'test' database
    collection = db['example_collection']
    # Insert a sample document to ensure the database is created
    collection.insert_one({"name": "sample"})

    # Verify the 'test' database is created
    databases = client.list_database_names()
    print("Updated Databases:", databases)

    client.close()
except Exception as e:
    print("Failed to connect to MongoDB server.")
    print("Error:", e)

以上测试。

相关推荐
RainbowSea1 小时前
9-1. MySQL 性能分析工具的使用——last\_query\_cost,慢查询日志
数据库·sql·mysql
Sui_Network1 小时前
Sui 如何支持各种类型的 Web3 游戏
大数据·数据库·人工智能·游戏·web3·区块链
ZKNOW甄知科技1 小时前
IT服务运营管理体系的常用方法论与实践指南(上)
大数据·数据库·人工智能
黄雪超2 小时前
深入HBase——核心组件
数据结构·数据库·hbase
qq_529835354 小时前
Redis作为缓存和数据库的数据一致性问题
数据库·redis·缓存
山猪打不过家猪9 小时前
ASP.NET Core Clean Architecture
java·数据库·asp.net
qwy7152292581639 小时前
13-R数据重塑
服务器·数据库·r语言
Bio Coder9 小时前
R语言安装生物信息数据库包
开发语言·数据库·r语言
钊兵10 小时前
数据库驱动免费下载(Oracle、Mysql、达梦、Postgresql)
数据库·mysql·postgresql·oracle·达梦·驱动