参考:
- 在服务端操作 MongoDB:https://docs.mongodb.com/drivers/
- 在 Node.js 中操作 MongoDB:https://docs.mongodb.com/drivers/node/
初始化示例项目
mkdir node-mongodb-democd node-mongodb-demonpm init -ynpm install mongodb
连接到 MongoDB
const { MongoClient } = require("mongodb");// Connection URIconst uri ="mongo://127.0.0.1:27017";// Create a new MongoClientconst client = new MongoClient(uri);async function run() {try {// Connect the client to the serverawait client.connect();// Establish and verify connectionawait client.db("admin").command({ ping: 1 });console.log("Connected successfully to server");} catch () {console.log('Connect failed')} finally {// Ensures that the client will close when you finish/errorawait client.close();}}run()
CRUD 操作
CRUD(创建,读取,更新,删除)操作使您可以处理存储在 MongoDB 中的数据。
创建文档
插入一个:
const pizzaDocument = {name: "Neapolitan pizza",shape: "round",toppings: [ "San Marzano tomatoes", "mozzarella di bufala cheese" ],};const result = await pizzaCollection.insertOne(pizzaDocument);console.dir(result.insertedCount);
插入多个:
const pizzaDocuments = [{ name: "Sicilian pizza", shape: "square" },{ name: "New York pizza", shape: "round" },{ name: "Grandma pizza", shape: "square" },];const result = pizzaCollection.insertMany(pizzaDocuments);console.dir(result.insertedCount);
查询文档
const findResult = await orders.find({name: "Lemony Snicket",date: {$gte: new Date(new Date().setHours(00, 00, 00)),$lt: new Date(new Date().setHours(23, 59, 59)),},});
删除文档
const doc = {pageViews: {$gt: 10,$lt: 32768}};// 删除符合条件的单个文档const deleteResult = await collection.deleteOne(doc);console.dir(deleteResult.deletedCount);// 删除符合条件的多个文档const deleteManyResult = await collection.deleteMany(doc);console.dir(deleteManyResult.deletedCount);
修改文档
更新1个文档:
const filter = { _id: 465 };// update the value of the 'z' field to 42const updateDocument = {$set: {z: 42,},};// 更新多个const result = await collection.updateOne(filter, updateDocument);// 更新多个const result = await collection.updateMany(filter, updateDocument);
替换文档:
const filter = { _id: 465 };// replace the matched document with the replacement documentconst replacementDocument = {z: 42,};const result = await collection.replaceOne(filter, replacementDocument);
