如何使用deleteMany()在MongoDB中删除多个文档?
让我们首先创建一个包含文档的集合 -
> db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b07bf3115999ed51214") } > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b0bbf3115999ed51215") } > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b0fbf3115999ed51216") } > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b12bf3115999ed51217") } > db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce00b18bf3115999ed51218") }
以下是使用find()方法显示集合中所有文档的查询 -
> db.deleteMultipleDocumentsDemo.find();
这将产生以下输出 -
{ "_id" : ObjectId("5ce00b07bf3115999ed51214"), "StudentFirstName" : "Larry" } { "_id" : ObjectId("5ce00b0bbf3115999ed51215"), "StudentFirstName" : "Chris" } { "_id" : ObjectId("5ce00b0fbf3115999ed51216"), "StudentFirstName" : "David" } { "_id" : ObjectId("5ce00b12bf3115999ed51217"), "StudentFirstName" : "Bob" } { "_id" : ObjectId("5ce00b18bf3115999ed51218"), "StudentFirstName" : "Carol" }
以下是MongoDB中删除多个文档的查询 -
> db.deleteMultipleDocumentsDemo.deleteMany({StudentFirstName: {$in: ["Larry", "David", "Carol"]}}); { "acknowledged" : true, "deletedCount" : 3 }
让我们再次显示文档 -
> db.deleteMultipleDocumentsDemo.find();
这将产生以下输出 -
{ "_id" : ObjectId("5ce00b0bbf3115999ed51215"), "StudentFirstName" : "Chris" } { "_id" : ObjectId("5ce00b12bf3115999ed51217"), "StudentFirstName" : "Bob" }
广告