20231105000000_move_doc_versions_from_docops_to_docs.mjs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import mongodbLegacy from 'mongodb'
  2. import { db, getCollectionInternal } from './lib/mongodb.mjs'
  3. const { ObjectId, ReadPreference } = mongodbLegacy
  4. const BATCH_SIZE = parseInt(process.env.BATCH_SIZE || '1000', 10)
  5. const MIN_ID = process.env.MIN_ID
  6. const tags = ['server-ce', 'server-pro', 'saas']
  7. const migrate = async () => {
  8. const docOps = await getCollectionInternal('docOps')
  9. const filter = {}
  10. if (MIN_ID) {
  11. filter._id = { $gte: new ObjectId(MIN_ID) }
  12. }
  13. const records = docOps
  14. .find(filter, { readPreference: ReadPreference.secondaryPreferred })
  15. .sort({ _id: 1 })
  16. let docsProcessed = 0
  17. let batch = []
  18. for await (const record of records) {
  19. const docId = record.doc_id
  20. const version = record.version
  21. batch.push({
  22. updateOne: {
  23. filter: {
  24. _id: docId,
  25. version: { $exists: false },
  26. },
  27. update: { $set: { version } },
  28. },
  29. })
  30. if (batch.length >= BATCH_SIZE) {
  31. await db.docs.bulkWrite(batch, { ordered: false })
  32. batch = []
  33. }
  34. docsProcessed += 1
  35. if (docsProcessed % 100000 === 0) {
  36. console.log(`${docsProcessed} docs processed - last id: ${docId}`)
  37. }
  38. }
  39. if (batch.length > 0) {
  40. await db.docs.bulkWrite(batch, { ordered: false })
  41. }
  42. console.log(`DONE - ${docsProcessed} docs processed`)
  43. }
  44. const rollback = async ({ db }) => {
  45. // Nothing to do on rollback. We don't want to remove versions from the docs
  46. // collection because they might be more current than the ones in the docOps
  47. // collection.
  48. }
  49. export default {
  50. tags,
  51. migrate,
  52. rollback,
  53. }