/

How to Remove All Items from a MongoDB Collection

How to Remove All Items from a MongoDB Collection

When working with MongoDB, there may be instances where you need to remove all items from a collection. In this article, we will discuss how to achieve this using the deleteMany method.

To remove all items from a MongoDB collection, you can simply call the deleteMany method on the collection and pass an empty object as the filter. Here is an example:

1
yourcollection.deleteMany({})

Here’s a complete example that demonstrates how to remove all items from a MongoDB collection using Node.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const mongo = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017'
let db, jobs

mongo.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, client) => {
if (err) {
console.error(err)
return
}
db = client.db('jobs')
jobs = db.collection('jobs')

jobs.deleteMany({})
})

By calling the deleteMany method with an empty object, you are essentially specifying that you want to remove all documents from the collection.

In the example above, we first establish a connection to the MongoDB server using mongo.connect. Then, we access the desired database and collection. Finally, we call the deleteMany method on the jobs collection, passing an empty object as the filter.

That’s it! Now you know how to remove all items from a MongoDB collection using the deleteMany method. This can be useful when you need to clean up a collection or start fresh with a clean slate.

tags: [“mongodb”, “node.js”, “deleteMany”, “collection”, “database”]