// 引入MongoDB的Node.js驱动程序
const MongoClient = require('mongodb').MongoClient;
// 定义MongoDB连接字符串和选项
const url = 'mongodb://localhost:27017/mydb';
const options = {
useNewUrlParser: true,
useUnifiedTopology: true
};
// 连接MongoDB服务器
MongoClient.connect(url, options, function(err, client) {
if (err) throw err;
// 获取MongoDB数据库实例
const db = client.db('mydb');
// 创建集合和分片键
const collectionName = 'mycollection';
const shardKey = { _id: 'hashed' };
// 创建集合和分片
db.createCollection(collectionName, function(err, collection) {
if (err) throw err;
// 启用集合的分片功能
db.command({ enableSharding: collectionName }, function(err, result) {
if (err) throw err;
// 为集合添加分片键
db.command({ shardCollection: collectionName, key: shardKey }, function(err, result) {
if (err) throw err;
// 查看分片集群状态
db.command({ shardStatus: 1 }, function(err, result) {
if (err) throw err;
console.log(result);
client.close();
});
});
});
});
});
代码注释解释:
首先引入MongoDB的Node.js驱动程序。
定义MongoDB连接字符串和选项,包括数据库的地址和端口号、使用的协议和MongoDB驱动程序的选项等。
使用MongoDB的Node.js驱动程序连接MongoDB服务器,并获取MongoDB数据库实例。
定义需要创建的集合名称和分片键,其中分片键使用_id字段的哈希值。
使用MongoDB的createCollection方法创建集合,并传入回调函数处理结果。在回调函数中进行集合分片的相关操作。
调用MongoDB的enableSharding方法启用集合的分片功能。
调用MongoDB的shardCollection方法为集合添加分片键,并指定分片键为_id的哈希值。
调用MongoDB的shardStatus方法查看分片集群状态,并在控制台输出结果。
最后关闭MongoDB数据库连接。
这段示例代码演示了如何使用MongoDB的Node.js驱动程序创建一个带有分片功能的集合,并添加分片键进行分片。在实际应用中,需要根据实际需求进行相应的配置和管理工作,以保证MongoDB分片集群的稳定性和可靠性。
感谢您的来访,获取更多精彩文章请收藏本站。
© 版权声明
THE END