@@ -9,31 +9,49 @@ async function addDisabledToAddressregister() {
99
1010 const collection = db . collection ( 'addressregister' ) ;
1111
12- const totalToMigrate = await collection . countDocuments ( { disabled : { $exists : false } } ) ;
12+ // Get current max id
13+ const maxIdDoc = await collection . find ( { } ) . sort ( { _id : - 1 } ) . limit ( 1 ) . toArray ( ) ;
14+ const maxIdAtStart = maxIdDoc . length > 0 ? maxIdDoc [ 0 ] . _id : null ;
15+
16+ if ( ! maxIdAtStart ) {
17+ log ( 'No documents found. Migration skipped.' ) ;
18+ return ;
19+ }
20+
21+ const totalToMigrate = await collection . countDocuments ( {
22+ disabled : { $exists : false } ,
23+ _id : { $lte : maxIdAtStart } // Only count documents that exist now
24+ } ) ;
1325
1426 if ( totalToMigrate === 0 ) {
1527 log ( 'All documents already have disabled field. Migration skipped.' ) ;
1628 return ;
1729 }
1830
19- log ( `Migrating ${ totalToMigrate } documents in batches of ${ BATCH_SIZE } ...` ) ;
31+ log ( `Migrating ${ totalToMigrate } documents (up to _id: ${ maxIdAtStart } ) in batches of ${ BATCH_SIZE } ...` ) ;
2032
2133 let processedCount = 0 ;
2234 let batchNumber = 0 ;
23-
35+ let lastId = null ;
2436 let running = true ;
2537
2638 while ( running ) {
27- // Find batch of documents without the field
39+ const query = {
40+ disabled : { $exists : false } ,
41+ _id : { $lte : maxIdAtStart } // Cap at migration start
42+ } ;
43+
44+ // cursor based pagination
45+ if ( lastId ) {
46+ query . _id . $gt = lastId ;
47+ }
48+
49+ // Find batch of documents without the field and capped at max id
2850 const batch = await collection
29- . find (
30- { disabled : { $exists : false } } ,
31- {
32- projection : {
33- _id : true
34- }
35- }
36- )
51+ . find ( query , {
52+ projection : { _id : true }
53+ } )
54+ . sort ( { _id : 1 } )
3755 . limit ( BATCH_SIZE )
3856 . toArray ( ) ;
3957
@@ -49,8 +67,11 @@ async function addDisabledToAddressregister() {
4967 processedCount += result . modifiedCount ;
5068 batchNumber ++ ;
5169
52- if ( batchNumber % 10 === 0 ) {
53- log ( `Progress: ${ processedCount } /${ totalToMigrate } (${ ( ( processedCount / totalToMigrate ) * 100 ) . toFixed ( 1 ) } %)` ) ;
70+ // Update lastId for next iteration
71+ lastId = batch [ batch . length - 1 ] . _id ;
72+
73+ if ( totalToMigrate < 50000 || batchNumber % 10 === 0 ) {
74+ log ( `Progress: Batch ${ batchNumber } - ${ processedCount } /${ totalToMigrate } (${ ( ( processedCount / totalToMigrate ) * 100 ) . toFixed ( 1 ) } %)` ) ;
5475 }
5576 }
5677
0 commit comments