Sitemap

Mongo Delete All ancestors By Id

2 min readJan 11, 2025

--

Assuming we have a relation of children and parents and one of our fields is ancestors of array of parents and their parents. If we want to delete all children of a specific parent, here’s what we will do. To delete all items in MongoDB where the field ancestor contains any value from the array ["XYZ"], you can use the $in operator in your query. Here’s how you can do it in MongoDB Compass:

  1. Open MongoDB Compass and connect to your database.
  2. Navigate to the desired collection.
  3. Click on the “Aggregations” tab or use the query bar for “Filter”.
  4. Use the following query in the query bar or filter:

Query:

{ "ancestor": { "$in": ["XYZ"] } }
  1. Click on the “Delete Many” option to remove all matching documents.
Press enter or click to view image in full size

Note: you might want to use objectId as seen above!

Get Lior Amsalem’s stories in your inbox

Join Medium for free to get updates from this writer.

Alternatively, using the MongoDB shell or programmatically:

Programmatic Approach:

If you’re running the query programmatically, the deleteMany method is appropriate.

Example in Node.js:

const { MongoClient } = require("mongodb");

async function deleteItems() {
const uri = "your_mongodb_connection_string";
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db("your_database_name");
const collection = database.collection("your_collection_name");
const result = await collection.deleteMany({
ancestor: { $in: ["XYZ"] } // you might want to use ObjectID here
});
console.log(`${result.deletedCount} document(s) were deleted.`);
} finally {
await client.close();
}
}
deleteItems().catch(console.error);

Replace your_mongodb_connection_string, your_database_name, and your_collection_name with your specific details.

--

--