参考:

初始化示例项目

  1. mkdir node-mongodb-demo
  2. cd node-mongodb-demo
  3. npm init -y
  4. npm install mongodb

连接到 MongoDB

  1. const { MongoClient } = require("mongodb");
  2. // Connection URI
  3. const uri =
  4. "mongo://127.0.0.1:27017";
  5. // Create a new MongoClient
  6. const client = new MongoClient(uri);
  7. async function run() {
  8. try {
  9. // Connect the client to the server
  10. await client.connect();
  11. // Establish and verify connection
  12. await client.db("admin").command({ ping: 1 });
  13. console.log("Connected successfully to server");
  14. } catch () {
  15. console.log('Connect failed')
  16. } finally {
  17. // Ensures that the client will close when you finish/error
  18. await client.close();
  19. }
  20. }
  21. run()

CRUD 操作

CRUD(创建,读取,更新,删除)操作使您可以处理存储在 MongoDB 中的数据。

创建文档

插入一个:

  1. const pizzaDocument = {
  2. name: "Neapolitan pizza",
  3. shape: "round",
  4. toppings: [ "San Marzano tomatoes", "mozzarella di bufala cheese" ],
  5. };
  6. const result = await pizzaCollection.insertOne(pizzaDocument);
  7. console.dir(result.insertedCount);

插入多个:

  1. const pizzaDocuments = [
  2. { name: "Sicilian pizza", shape: "square" },
  3. { name: "New York pizza", shape: "round" },
  4. { name: "Grandma pizza", shape: "square" },
  5. ];
  6. const result = pizzaCollection.insertMany(pizzaDocuments);
  7. console.dir(result.insertedCount);

查询文档

  1. const findResult = await orders.find({
  2. name: "Lemony Snicket",
  3. date: {
  4. $gte: new Date(new Date().setHours(00, 00, 00)),
  5. $lt: new Date(new Date().setHours(23, 59, 59)),
  6. },
  7. });

删除文档

  1. const doc = {
  2. pageViews: {
  3. $gt: 10,
  4. $lt: 32768
  5. }
  6. };
  7. // 删除符合条件的单个文档
  8. const deleteResult = await collection.deleteOne(doc);
  9. console.dir(deleteResult.deletedCount);
  10. // 删除符合条件的多个文档
  11. const deleteManyResult = await collection.deleteMany(doc);
  12. console.dir(deleteManyResult.deletedCount);

修改文档

更新1个文档:

  1. const filter = { _id: 465 };
  2. // update the value of the 'z' field to 42
  3. const updateDocument = {
  4. $set: {
  5. z: 42,
  6. },
  7. };
  8. // 更新多个
  9. const result = await collection.updateOne(filter, updateDocument);
  10. // 更新多个
  11. const result = await collection.updateMany(filter, updateDocument);

替换文档:

  1. const filter = { _id: 465 };
  2. // replace the matched document with the replacement document
  3. const replacementDocument = {
  4. z: 42,
  5. };
  6. const result = await collection.replaceOne(filter, replacementDocument);