How to delete partial data in MongoDB?

To delete partial data in MongoDB, you can combine find() with skip() and limit() methods to target specific documents, then use deleteMany() with the $in operator to remove them efficiently.

Syntax

var ids = db.collection.find({}, {_id: 1}).skip(N).toArray().map(function(d) { 
    return d._id; 
});
db.collection.deleteMany({_id: {$in: ids}});

Sample Data

db.demo488.insertMany([
    {"Name": "Chris"},
    {"Name": "David"},
    {"Name": "Bob"},
    {"Name": "Mike"},
    {"Name": "Sam"},
    {"Name": "John"},
    {"Name": "Robert"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e8351e0b0f3fa88e22790b2"),
        ObjectId("5e8351e8b0f3fa88e22790b3"),
        ObjectId("5e8351ebb0f3fa88e22790b4"),
        ObjectId("5e8351eeb0f3fa88e22790b5"),
        ObjectId("5e835202b0f3fa88e22790b6"),
        ObjectId("5e835207b0f3fa88e22790b7"),
        ObjectId("5e83520cb0f3fa88e22790b8")
    ]
}

View All Documents

db.demo488.find();
{ "_id": ObjectId("5e8351e0b0f3fa88e22790b2"), "Name": "Chris" }
{ "_id": ObjectId("5e8351e8b0f3fa88e22790b3"), "Name": "David" }
{ "_id": ObjectId("5e8351ebb0f3fa88e22790b4"), "Name": "Bob" }
{ "_id": ObjectId("5e8351eeb0f3fa88e22790b5"), "Name": "Mike" }
{ "_id": ObjectId("5e835202b0f3fa88e22790b6"), "Name": "Sam" }
{ "_id": ObjectId("5e835207b0f3fa88e22790b7"), "Name": "John" }
{ "_id": ObjectId("5e83520cb0f3fa88e22790b8"), "Name": "Robert" }

Delete Documents Starting from Position 5

Delete all documents from the 5th position onwards (skip first 4 documents) ?

var deleteData = db.demo488.find({}, {_id: 1}).skip(4).toArray().map(function(d) { 
    return d._id; 
});
db.demo488.deleteMany({_id: {$in: deleteData}});
WriteResult({ "nRemoved": 3 })

Verify Result

db.demo488.find();
{ "_id": ObjectId("5e8351e0b0f3fa88e22790b2"), "Name": "Chris" }
{ "_id": ObjectId("5e8351e8b0f3fa88e22790b3"), "Name": "David" }
{ "_id": ObjectId("5e8351ebb0f3fa88e22790b4"), "Name": "Bob" }
{ "_id": ObjectId("5e8351eeb0f3fa88e22790b5"), "Name": "Mike" }

How It Works

  • find({}, {_id: 1}) retrieves only the _id field of all documents
  • skip(4) skips the first 4 documents
  • toArray().map() converts the cursor to an array of _id values
  • deleteMany({_id: {$in: ids}}) removes all documents whose _id matches the collected IDs

Conclusion

Use skip() with find() to identify partial data ranges, then deleteMany() with $in operator to efficiently remove multiple documents. This approach provides precise control over which portion of your data to delete.

Updated on: 2026-03-15T03:08:55+05:30

317 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements