mirror of
https://github.com/overleaf/overleaf.git
synced 2024-12-28 05:32:34 +00:00
e25d8b1440
Extend batchedUpdate to accept find() options, and use a hint in upgrade script query to suggest mongo uses the _id index GitOrigin-RevId: 7115f84d8be0c78ccb443051e911c931bf4aa0de
92 lines
2 KiB
JavaScript
92 lines
2 KiB
JavaScript
const { ReadPreference, ObjectId } = require('mongodb')
|
|
const { db, waitForDb } = require('../../app/src/infrastructure/mongodb')
|
|
|
|
const BATCH_SIZE = parseInt(process.env.BATCH_SIZE, 10) || 1000
|
|
let BATCH_LAST_ID
|
|
if (process.env.BATCH_LAST_ID) {
|
|
BATCH_LAST_ID = ObjectId(process.env.BATCH_LAST_ID)
|
|
}
|
|
|
|
async function getNextBatch(collection, query, maxId, projection, options) {
|
|
maxId = maxId || BATCH_LAST_ID
|
|
if (maxId) {
|
|
query._id = { $gt: maxId }
|
|
}
|
|
const entries = await collection
|
|
.find(query, options)
|
|
.project(projection)
|
|
.sort({ _id: 1 })
|
|
.limit(BATCH_SIZE)
|
|
.toArray()
|
|
return entries
|
|
}
|
|
|
|
async function performUpdate(collection, nextBatch, update) {
|
|
return collection.updateMany(
|
|
{ _id: { $in: nextBatch.map(entry => entry._id) } },
|
|
update
|
|
)
|
|
}
|
|
|
|
async function batchedUpdate(
|
|
collectionName,
|
|
query,
|
|
update,
|
|
projection,
|
|
options
|
|
) {
|
|
await waitForDb()
|
|
const collection = db[collectionName]
|
|
|
|
options = options || {}
|
|
options.readPreference = ReadPreference.SECONDARY
|
|
|
|
projection = projection || { _id: 1 }
|
|
let nextBatch
|
|
let updated = 0
|
|
let maxId
|
|
while (
|
|
(nextBatch = await getNextBatch(
|
|
collection,
|
|
query,
|
|
maxId,
|
|
projection,
|
|
options
|
|
)).length
|
|
) {
|
|
maxId = nextBatch[nextBatch.length - 1]._id
|
|
updated += nextBatch.length
|
|
console.log(
|
|
`Running update on batch with ids ${JSON.stringify(
|
|
nextBatch.map(entry => entry._id)
|
|
)}`
|
|
)
|
|
|
|
if (typeof update === 'function') {
|
|
await update(collection, nextBatch)
|
|
} else {
|
|
await performUpdate(collection, nextBatch, update)
|
|
}
|
|
|
|
console.error(`Completed batch ending ${maxId}`)
|
|
}
|
|
return updated
|
|
}
|
|
|
|
function batchedUpdateWithResultHandling(collection, query, update) {
|
|
batchedUpdate(collection, query, update)
|
|
.then(updated => {
|
|
console.error({ updated })
|
|
process.exit(0)
|
|
})
|
|
.catch(error => {
|
|
console.error({ error })
|
|
process.exit(1)
|
|
})
|
|
}
|
|
|
|
module.exports = {
|
|
getNextBatch,
|
|
batchedUpdate,
|
|
batchedUpdateWithResultHandling,
|
|
}
|