Skip to content

Node.js MongoDB

安装

bash
npm install mongodb

连接与获取集合

javascript
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

async function run() {
  await client.connect();
  const db = client.db("mydb");
  const coll = db.collection("users");
  // 操作...
  await client.close();
}
run().catch(console.dir);

插入文档

javascript
await coll.insertOne({ name: "张三", age: 28 });
const result = await coll.insertMany([
  { name: "李四", age: 25 },
  { name: "王五", age: 30 }
]);

查询

javascript
const one = await coll.findOne({ name: "张三" });
const cursor = coll.find({ age: { $gte: 18 } });
for await (const doc of cursor) {
  console.log(doc);
}

更新与删除

javascript
await coll.updateOne(
  { name: "张三" },
  { $set: { age: 29 } }
);
await coll.deleteOne({ name: "李四" });

聚合

javascript
const pipeline = [
  { $match: { status: "active" } },
  { $group: { _id: "$city", count: { $sum: 1 } } }
];
const cursor = coll.aggregate(pipeline);
const docs = await cursor.toArray();

更多 API 见 MongoDB Node.js Driver。下一节进入 MongoDB 高级教程 - 关系