How to delete multiple ids in MongoDB?

To delete multiple documents by their IDs in MongoDB, use the $in operator with the remove() or deleteMany() method. This allows you to specify multiple ObjectIds in a single query.

Syntax

db.collectionName.remove({ 
    _id: { $in: [ObjectId("id1"), ObjectId("id2"), ObjectId("id3")] } 
});

Or using the modern deleteMany() method:

db.collectionName.deleteMany({ 
    _id: { $in: [ObjectId("id1"), ObjectId("id2"), ObjectId("id3")] } 
});

Sample Data

db.deleteMultipleIdsDemo.insertMany([
    {"ClientName": "Chris", "ClientAge": 26},
    {"ClientName": "Robert", "ClientAge": 28},
    {"ClientName": "Sam", "ClientAge": 25},
    {"ClientName": "John", "ClientAge": 34},
    {"ClientName": "Carol", "ClientAge": 36}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c9cd7d6a629b87623db1b19"),
        ObjectId("5c9cd7dea629b87623db1b1a"),
        ObjectId("5c9cd7e9a629b87623db1b1b"),
        ObjectId("5c9cd7f7a629b87623db1b1c"),
        ObjectId("5c9cd803a629b87623db1b1d")
    ]
}

View All Documents

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
}

Delete Multiple IDs

db.deleteMultipleIdsDemo.remove({ 
    _id: { 
        $in: [
            ObjectId("5c9cd7dea629b87623db1b1a"),
            ObjectId("5c9cd803a629b87623db1b1d"),
            ObjectId("5c9cd7d6a629b87623db1b19")
        ] 
    } 
});
WriteResult({ "nRemoved": 3 })

Verify Result

db.deleteMultipleIdsDemo.find().pretty();
{
    "_id": ObjectId("5c9cd7e9a629b87623db1b1b"),
    "ClientName": "Sam",
    "ClientAge": 25
}
{
    "_id": ObjectId("5c9cd7f7a629b87623db1b1c"),
    "ClientName": "John",
    "ClientAge": 34
}

Conclusion

Use the $in operator to delete multiple documents by their IDs in a single MongoDB query. This approach is efficient for batch deletions and returns the count of deleted documents.

Updated on: 2026-03-15T00:35:36+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements