Node.js 如何删除 MongoDB 数据?

文章导读
上一个 测验 下一个 Node.js 的 mongodb 驱动在 Collection class 中提供了两个方法。deleteOne() 方法删除一个文档,而 deleteMany() 方法用于一次性删除多个文档。两种方法都需要一个 filter 参数。
📋 目录
  1. A deleteOne()
  2. B deleteMany()
  3. C 删除 Collection
A A

Node.js - MongoDB 删除



上一个
测验
下一个

Node.js 的 mongodb 驱动在 Collection class 中提供了两个方法。deleteOne() 方法删除一个文档,而 deleteMany() 方法用于一次性删除多个文档。两种方法都需要一个 filter 参数。

collection.deleteOne(filter);

请注意,如果有多个文档满足给定的 filter 条件,则只会删除第一个文档。

deleteOne()

在下面的示例中,deleteOne() 方法从 products collection 中删除 name 字段匹配 "TV" 的文档。

const {MongoClient} = require('mongodb');
async function main(){

   const uri = "mongodb://localhost:27017/";
   const client = new MongoClient(uri);

   try {
      await client.connect();
      await deldocs(client, "mydb", "products");
   } finally {
      await client.close();
   }
}

main().catch(console.error);


async function deldocs(client, dbname, colname){
   var myqry = { Name: "TV" };
   const result = await client.db(dbname).collection(colname).deleteOne(myqry);
   console.log("文档已删除");
}

使用 MongoCompass(或 MongoShell)验证上述代码执行后,预期的文档是否已被删除。

deleteMany()

deleteMany() 方法同样使用 filter 参数。不过,它会删除所有满足指定条件的文档。

在上方的代码中,将 deldocs() 函数修改如下。将删除所有 price>10000 的文档。

async function deldocs(client, dbname, colname){
   var myqry = {"price":{$gt:10000}};
   const result = await client.db(dbname).collection(colname).deleteMany(myqry);
   console.log("文档已删除");
}

删除 Collection

你可以使用 drop() 方法从数据库中删除一个 collection。

示例

const {MongoClient} = require('mongodb');

async function main(){

   const uri = "mongodb://localhost:27017/";
   const client = new MongoClient(uri);

   try {
      await client.connect();
      await dropcol(client, "mydb", "products");
   } finally {
      await client.close();
   }
}
main().catch(console.error);


async function dropcol(client, dbname, colname){
   const result = await client.db(dbname).collection(colname).drop();
   console.log("Collection 已删除 ");
}

db 对象还提供了 dropCollection() 方法。

const {MongoClient} = require('mongodb');
async function main(){
   
	const uri = "mongodb://localhost:27017/";
   const client = new MongoClient(uri);

   try {
      await client.connect();
      await dropcol(client, "mydb", "orders");
   } finally {
      await client.close();
   }
}

main().catch(console.error);

async function dropcol(client, dbname, colname){
   const result = await client.db(dbname).dropCollection(colname);
   console.log("Collection 已删除");
}