mongoDb删除数据实例教程

发布时间:2020-05-28编辑:脚本学堂
本文介绍了mongodb数据库中删除数据的方法,主要通过remove()命令实现,基本语法:db.集合名称.remove(键值对),需要的朋友参考下。

mongoDb插入数据比较简单,删除数据也不复杂,主要通过remove()命令实现操作。
基本语法:db.集合名称.remove(键值对)

例如:

复制代码 代码示例:
>db.testCollection.save({f1:'59biye',f2:'com'})    (回车)
>db.testCollection.save({f1:'59biye1',f2:'com'})   (回车)
>db.testCollection.save({f1:'59biye2',f2:'com'})   (回车)
>db.testCollection.save({f1:'59biye3',f2:'com'})   (回车)
>db.testCollection.save({f1:'59biye4',f2:'com'})   (回车)
>db.testCollection.save({f1:'59biye5',f2:'com'})   (回车)
>db.testCollection.save({f1:'59biye6',f2:'com'})   (回车)
>db.testCollection.find()  (回车)

看到运行结果:
 

复制代码 代码示例:

{ "_id" : ObjectId("50ee5c9d04a94efb10bc7fb9"), "f1" : "59biye", "f2" : "com" }
{ "_id" : ObjectId("50ee5ca304a94efb10bc7fba"), "f1" : "59biye1", "f2" : "com" }

{ "_id" : ObjectId("50ee5ca604a94efb10bc7fbb"), "f1" : "59biye2", "f2" : "com" }

{ "_id" : ObjectId("50ee5caa04a94efb10bc7fbc"), "f1" : "59biye3", "f2" : "com" }

{ "_id" : ObjectId("50ee5cae04a94efb10bc7fbd"), "f1" : "59biye4", "f2" : "com" }

{ "_id" : ObjectId("50ee5cb204a94efb10bc7fbe"), "f1" : "59biye5", "f2" : "com" }

{ "_id" : ObjectId("50ee5cb604a94efb10bc7fbf"), "f1" : "59biye6", "f2" : "com" }

想要删除f1值为59biye的数据,操作:
 

复制代码 代码示例:
>db.testCollection.remove({f1:'59biye'}) (回车)
>db.testCollection.find()  (回车)

可以看到运行结果变成如下了,那条数据被删除了:
 

复制代码 代码示例:

{ "_id" : ObjectId("50ee5ca304a94efb10bc7fba"), "f1" : "59biye1", "f2" : "com" }

{ "_id" : ObjectId("50ee5ca604a94efb10bc7fbb"), "f1" : "59biye2", "f2" : "com" }

{ "_id" : ObjectId("50ee5caa04a94efb10bc7fbc"), "f1" : "59biye3", "f2" : "com" }

{ "_id" : ObjectId("50ee5cae04a94efb10bc7fbd"), "f1" : "59biye4", "f2" : "com" }

{ "_id" : ObjectId("50ee5cb204a94efb10bc7fbe"), "f1" : "59biye5", "f2" : "com" }

{ "_id" : ObjectId("50ee5cb604a94efb10bc7fbf"), "f1" : "59biye6", "f2" : "com" }

同理,如果要删除f2为com的数据那?操作如下:
 

复制代码 代码示例:
>db.testCollection.remove({f2:'com'}) (回车)
>db.testCollection.find()  (回车)

一条数据也没有了,成功删除。