目录

  1. MongoDB 连接概述
  2. 使用 MongoDB Shell 连接
  3. 在应用程序中连接 MongoDB
  4. 连接 URI 格式
  5. 连接到副本集和分片集群
  6. 参考资料

MongoDB 连接概述

MongoDB 提供了多种方式来连接数据库,包括使用 MongoDB Shell、应用程序驱动(如 Java、Python、Node.js 等)以及通过 MongoDB URI 连接。通过适当配置和连接,您可以与 MongoDB 数据库进行交互、查询和管理数据。

使用 MongoDB Shell 连接

MongoDB 提供了 MongoDB Shell(mongo 命令),它允许您从命令行直接连接到数据库。基本的连接命令如下:

mongo --host <hostname> --port <port> --username <username> --password <password> --authenticationDatabase <authenticationDB>

  • --host:MongoDB 服务器的地址(如果是本地连接,则为 localhost)。
  • --port:MongoDB 服务运行的端口(默认为 27017)。
  • --username--password:用于身份验证的用户名和密码。
  • --authenticationDatabase:指定进行身份验证的数据库,通常为 admin 数据库。

例如,连接到本地 MongoDB 实例的命令可能如下:

mongo --host localhost --port 27017 --username admin --password secret --authenticationDatabase admin

在应用程序中连接 MongoDB

MongoDB 提供了多种编程语言的驱动程序,您可以在自己的应用程序中使用这些驱动程序连接到 MongoDB。例如,以下是在 Node.js 中连接 MongoDB 的示例:

Node.js 连接 MongoDB 示例:

  1. 安装 MongoDB 驱动程序:
npm install mongodb

  1. 使用 Node.js 代码连接到 MongoDB:
const { MongoClient } = require('mongodb');

const uri = "mongodb://username:password@localhost:27017/?authSource=admin";
const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();
    console.log("Connected to MongoDB!");
  } finally {
    await client.close();
  }
}

run().catch(console.error);

连接 URI 格式

MongoDB 使用 URI 格式来连接数据库。URI 格式允许您指定 MongoDB 实例的位置、端口、认证信息等。

以下是常见的连接 URI 格式:

  • 基本连接 URImongodb://<username>:<password>@<host>:<port>/<database>
  • 包含认证信息mongodb://<username>:<password>@<host>:<port>/<database>?authSource=admin
  • 连接副本集mongodb://<username>:<password>@<host1>:<port1>,<host2>:<port2>,<host3>:<port3>/<database>?replicaSet=<replicaSetName>
  • 连接到分片集群mongodb://<username>:<password>@<shard1>:<port1>,<shard2>:<port2>,<shard3>:<port3>/<database>?replicaSet=<replicaSetName>&readPreference=nearest

连接到副本集和分片集群

如果您的 MongoDB 部署使用副本集或分片集群,可以通过 URI 格式连接到副本集或分片集群。

连接副本集:

副本集是 MongoDB 的数据冗余机制,可以提高数据的可用性和稳定性。连接副本集时,您需要提供副本集成员的多个主机名或 IP 地址。

示例:

mongodb://user:password@host1:27017,host2:27017,host3:27017/mydb?replicaSet=myReplicaSet

连接分片集群:

如果您正在连接分片集群,您需要提供分片的 mongos 路由地址,MongoDB 会自动将请求路由到正确的分片。

示例:

mongodb://user:password@mongos1:27017,mongos2:27017/mongodb_db?readPreference=nearest


参考资料


如需更详细的信息或帮助,请访问 www.52kanjuqing.com