Created
June 10, 2020 08:38
-
-
Save Able1991/8719d17dcb097af5848f79a8885fe69e to your computer and use it in GitHub Desktop.
Batch update large collection with mongoose
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
schema.static("batchUpdate", async function batchUpdate(query, update) { | |
const batchSize = 100; | |
const first = await this.findOne(query, null, { sort: "_id" }); | |
if (!first) { | |
return; | |
} | |
query.firstId = first.id; | |
const updateBatch = async () => { | |
if (!query.firstId) { | |
return; | |
} | |
const { firstId, ...updateQuery } = query; | |
const [last] = await this.find( | |
{ | |
_id: { $gt: firstId }, | |
...updateQuery, | |
}, | |
null, | |
{ | |
sort: "_id", | |
limit: 1, | |
skip: batchSize, | |
} | |
); | |
const lastId = last ? last.id : null; | |
if (lastId || firstId) { | |
updateQuery["_id"] = {}; | |
if (firstId) { | |
updateQuery["_id"]["$gt"] = firstId; | |
} | |
if (lastId) { | |
updateQuery["_id"]["$lte"] = lastId; | |
} | |
} | |
await this.updateMany(updateQuery, update); | |
query.firstId = lastId; | |
await updateBatch(); | |
}; | |
return updateBatch(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment