前提需先打开MongoDB的服务端mongod --dbpath "D:/MongoDB/data/db"
const MongoClient = require('mongodb').MongoClient;
// 数据库地址
const url = 'mongodb://localhost:27017';
// 数据库名
const dbName = 'test';
// 连接数据库
MongoClient.connect(url, (err, client) => {
if(err) throw err; //连接异常
// 获取db对象,再获取集合对象
const col = client.db(dbName).collection('createIndexExamplel');
col.insert([
{a: 1, b:1},
{a: 2, b:2},
{a: 3, b:3},
{a: 4, b:4},
{a: 5, b:5},
], (err, result) => {
if(err) throw err; //插入异常
col.find().toArray((err, docs) => {
if(err) throw err; //查询异常
console.log("---查询结果---");
console.log(docs);
client.close(); // 关闭连接
})
})
})