- 实列化mongo连接
const { MongoClient } = require("mongodb");
const url = "mongodb://localhost:27017";
const client = new MongoClient(url);
- 定义连接方法
async function main() {
// 连接db
await client.connect();
// 获取Database
const db = client.db(dbName);
// 获取collection
const collection = db.collection("users");
}
3.操作数据库(拿到collection后)
//查看所有
const findResult = await collection.find({}).toArray();
console.log("Found documents =>", findResult);
//批量插入数据
const insertResult = await collection.insertMany([{ name: "Mr.zhang", age: 26, sex: "男" }]);
console.log("Inserted documents =>", insertResult);
//查找符合name="Mr.zhang"条件的数据
const filteredDocs = await collection.find({ name: "Mr.zhang" }).toArray();
console.log("Found documents filtered by { a: 3 } =>", filteredDocs);
//更新name="lisi"的age数据
const updateResult = await collection.updateOne({ name: "lisi" }, { $set: { age: 2 } });
console.log("Updated documents =>", updateResult);
//批量删除
const deleteResult = await collection.deleteMany({ name: "Mr.zhang" });
console.log("Deleted documents =>", deleteResult);
//创建name为下标1
const indexName = await collection.createIndex({ name: 1 });
console.log("index name =", indexName);
- 调用
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());