May 17, 2021 MongoDB
In the previous chapters we've learned how to add and update data to collections in MongoDB. In this section we will continue to learn about the deletion of the MongoDB collection.
The MongoDB remove() function is used to remove data from the collection.
MongoDB data updates can use the update() function. It is a good practice to execute the find() command before executing the remove() function to determine whether the conditions for execution are correct.
The basic syntax format of the remove() method is as follows:
db.collection.remove( <query>, <justOne> )
If your MongoDB is after version 2.6, the syntax format is as follows:
db.collection.remove( <query>, { justOne: <boolean>, writeConcern: <document> } )
Description of the parameters:
We perform two inserts in the following documents:
>db.col.insert({title: 'MongoDB 教程', description: 'MongoDB 是一个 Nosql 数据库', by: 'w3cschool', url: 'http://www.w3cschool.cn', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 })
Query the data using the find() function:
> db.col.find() { "_id" : ObjectId("56066169ade2f21f36b03137"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "w3cschool", "url" : "http://www.w3cschool.cn", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } { "_id" : ObjectId("5606616dade2f21f36b03138"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "w3cschool", "url" : "http://www.w3cschool.cn", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
Next we remove the document title for 'MongoDB Tutorial':
>db.col.remove({'title':'MongoDB 教程'}) WriteResult({ "nRemoved" : 2 }) # 删除了两条数据 >db.col.find() …… # 没有数据
If you only want to delete the first record found, you can set justOne to 1, as follows:
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
If you want to delete all your data, you can use the following method (like the truncate command for regular SQL):
>db.col.remove({}) >db.col.find() >