要在MongoDB中删除多个ID,可以使用$in运算符。以下是语法
db.yourCollectionName.remove( { _id : { $in: [yourObjectId1, yourObjectId2, yourObjectId3)] } } );
让我们创建包含文档的集合
> db.deleteMultipleIdsDemo.insertOne({"ClientName":"Chris","ClientAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd7d6a629b87623db1b19") } > db.deleteMultipleIdsDemo.insertOne({"ClientName":"Robert","ClientAge":28}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd7dea629b87623db1b1a") } > db.deleteMultipleIdsDemo.insertOne({"ClientName":"Sam","ClientAge":25}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd7e9a629b87623db1b1b") } > db.deleteMultipleIdsDemo.insertOne({"ClientName":"John","ClientAge":34}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd7f7a629b87623db1b1c") } > db.deleteMultipleIdsDemo.insertOne({"ClientName":"Carol","ClientAge":36}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd803a629b87623db1b1d") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.deleteMultipleIdsDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9cd7d6a629b87623db1b19"), "ClientName" : "Chris", "ClientAge" : 26 } { "_id" : ObjectId("5c9cd7dea629b87623db1b1a"), "ClientName" : "Robert", "ClientAge" : 28 } { "_id" : ObjectId("5c9cd7e9a629b87623db1b1b"), "ClientName" : "Sam", "ClientAge" : 25 } { "_id" : ObjectId("5c9cd7f7a629b87623db1b1c"), "ClientName" : "John", "ClientAge" : 34 } { "_id" : ObjectId("5c9cd803a629b87623db1b1d"), "ClientName" : "Carol", "ClientAge" : 36 }
以下是在MongoDB中删除多个ID的查询
> db.deleteMultipleIdsDemo.remove( { _id : { $in: [ObjectId("5c9cd7dea629b87623db1b1a"), ... ObjectId("5c9cd803a629b87623db1b1d"), ... ObjectId("5c9cd7d6a629b87623db1b19") ... ] } } ); WriteResult({ "nRemoved" : 3 })
让我们检查多个ID是否已删除
> db.deleteMultipleIdsDemo.find().pretty();
以下是显示我们已成功删除3个ID的输出,现在仅剩余2个
{ "_id" : ObjectId("5c9cd7e9a629b87623db1b1b"), "ClientName" : "Sam", "ClientAge" : 25 } { "_id" : ObjectId("5c9cd7f7a629b87623db1b1c"), "ClientName" : "John", "ClientAge" : 34 }