您可以remove()
为此使用。首先让我们创建一个包含文档的集合-
> db.deleteDataDemo.insertOne({_id:1,"Name":"Larry"}); { "acknowledged" : true, "insertedId" : 1 } > db.deleteDataDemo.insertOne({_id:2,"Name":"Chris"}); { "acknowledged" : true, "insertedId" : 2 } > db.deleteDataDemo.insertOne({_id:3,"Name":"Robert"}); { "acknowledged" : true, "insertedId" : 3 } > db.deleteDataDemo.insertOne({_id:4,"Name":"David"}); { "acknowledged" : true, "insertedId" : 4 } > db.deleteDataDemo.insertOne({_id:5,"Name":"Carol"}); { "acknowledged" : true, "insertedId" : 5 } > db.deleteDataDemo.insertOne({_id:6,"Name":"Sam"}); { "acknowledged" : true, "insertedId" : 6 }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.deleteDataDemo.find().pretty();
这将产生以下输出-
{ "_id" : 1, "Name" : "Larry" } { "_id" : 2, "Name" : "Chris" } { "_id" : 3, "Name" : "Robert" } { "_id" : 4, "Name" : "David" } { "_id" : 5, "Name" : "Carol" } { "_id" : 6, "Name" : "Sam" }
以下是通过使用多个条件从MongoDB中的集合中删除数据的查询。这里我们使用了两个条件,即_id 4和Name David-
> db.deleteDataDemo.remove({'_id':4,'Name':"David"}); WriteResult({ "nRemoved" : 1 })
让我们再次检查所有文件-
> db.deleteDataDemo.find().pretty();
这将产生以下输出-
{ "_id" : 1, "Name" : "Larry" } { "_id" : 2, "Name" : "Chris" } { "_id" : 3, "Name" : "Robert" } { "_id" : 5, "Name" : "Carol" } { "_id" : 6, "Name" : "Sam" }