• Node.js Video Tutorials

Node.js - MongoDB 刪除



Node.js 的 mongodb 驅動程式在 Collection 類中包含兩種方法。deleteOne() 方法刪除一個文件,而 deleteMany() 方法用於一次刪除多個文件。這兩種方法都需要一個 filter 引數。

collection.deleteOne(filter);

請注意,如果有多個文件滿足給定的過濾器條件,則只刪除第一個文件。

deleteOne()

在下面的例子中,deleteOne() 方法從 products 集合中刪除一個 name 欄位匹配 TV 的文件。

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

   const uri = "mongodb://: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("Document Deleted");
}

執行上述程式碼後,使用 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("Documents Deleted");
}

刪除集合

您可以使用 drop() 方法從資料庫中刪除集合。

示例

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

async function main(){

   const uri = "mongodb://: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 dropped ");

}

db 物件中還有一個可用的 **dropCollection()** 方法。

const {MongoClient} = require('mongodb');
async function main(){
   
	const uri = "mongodb://: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 dropped");
}
廣告