Last active
April 23, 2024 17:40
-
-
Save ride90/b3b34ab49822f7e2e35fc220afa680eb to your computer and use it in GitHub Desktop.
How to implement a cascade delete in MongoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// equivalent of cascade delete in MongoDB | |
/** | |
* Let's assume you have 2 related collections with next data structure. | |
* | |
* - `archive` | |
* { | |
* "_id" : ObjectId("5ce5138efe985e8424a79304"), | |
* "type" : "text", | |
* "headline" : "Curabitur non nulla sit amet nisl tempus convallis quis ac lectus." | |
* } | |
* - `archive_history` | |
* { | |
* "_id" : ObjectId("5ce51d46fe985e8438b7b8ed"), | |
* "item_id" : ObjectId("5ce5138efe985e8424a79304"), | |
* "action" : "fetch" | |
* } | |
* | |
* and you want to delete items from `archive` with some condition and also delete related records in `archive_history`. | |
* NOTE: limit is used in case of big amount of data.. | |
* NOTE: if mongo 3.6+, aggregation with `project`, `filter` might be used to avoid using `map` | |
**/ | |
var filterCondition = {type: "text"}; | |
var itemsCount = db.getCollection('archive').find(filterCondition).count() | |
var processed = 0; | |
var limit = 100; | |
print('Have ', itemsCount, ' items to delete.') | |
while (processed < itemsCount) { | |
// get `archive` IDs to delete | |
var itemsIDList = db.getCollection('archive') | |
.find(filterCondition, {_id: 1}) | |
.limit(limit) | |
.map(function (item) { | |
return item['_id'] | |
}); | |
print('Got ', itemsIDList.length, ' items IDs to delete.') | |
// delete related entries in `archive_history` | |
db.getCollection('archive_history') | |
.deleteMany( | |
{ | |
item_id: { | |
$in: itemsIDList | |
} | |
} | |
) | |
print('Deleted related entries in `archive_history`') | |
// after all delete items in `archive` | |
db.getCollection('archive') | |
.deleteMany( | |
{ | |
_id: { | |
$in: itemsIDList | |
} | |
} | |
) | |
print('Deleted items in `archive`') | |
// step ++ | |
processed += limit | |
} |
Amazing👌
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice idea!