const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost:27017";
const dbName = "demo";
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect(err => {
const db = client.db(dbName);
db.collection("student").insertOne(
{ name: "Cercei", age: 22 },
(err, result) => {
if (err) throw err;
console.log("数据插入成功");
client.close();
}
);
});
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost:27017";
const dbName = "demo";
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect(err => {
const db = client.db(dbName);
db.collection("student")
.find({})
.toArray((err, docs) => {
if (err) throw err;
console.log(docs);
client.close();
});
});
- 连接与查找数据库时间对比(主要时间耗费在数据库的连接上)
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost:27017";
const dbName = "demo";
const client = new MongoClient(url, { useUnifiedTopology: true });
console.time("connect");
client.connect(err => {
console.time("find");
const db = client.db(dbName);
db.collection("student")
.find({})
.toArray((err, docs) => {
if (err) throw err;
console.log(docs);
console.timeEnd("connect"); //connect: 1053.064ms
console.timeEnd("find"); //find: 22.595ms
client.close();
});
});
网友评论