|
| 1 | +package migration |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "time" |
| 7 | + |
| 8 | + "go.mongodb.org/mongo-driver/bson" |
| 9 | + "go.mongodb.org/mongo-driver/mongo/options" |
| 10 | +) |
| 11 | + |
| 12 | +func ChangeEsriAndStamenToDefault(ctx context.Context, c DBClient) error { |
| 13 | + col := c.WithCollection("property").Client() |
| 14 | + |
| 15 | + filter := bson.M{ |
| 16 | + "items.groups.fields.field": "tile_type", |
| 17 | + "items.groups.fields.value": bson.M{ |
| 18 | + "$in": bson.A{"esri_world_topo", "stamen_watercolor", "stamen_toner"}, |
| 19 | + }, |
| 20 | + } |
| 21 | + |
| 22 | + countCtx, cancel := context.WithTimeout(ctx, 30*time.Second) |
| 23 | + defer cancel() |
| 24 | + n, err := col.CountDocuments(countCtx, filter) |
| 25 | + if err != nil { |
| 26 | + return fmt.Errorf("count failed: %w", err) |
| 27 | + } |
| 28 | + fmt.Printf("[migration] target documents: %d\n", n) |
| 29 | + if n == 0 { |
| 30 | + fmt.Println("[migration] nothing to do") |
| 31 | + return nil |
| 32 | + } |
| 33 | + |
| 34 | + update := bson.M{ |
| 35 | + "$set": bson.M{ |
| 36 | + "items.$[i].groups.$[g].fields.$[f].value": "default", |
| 37 | + }, |
| 38 | + } |
| 39 | + arrayFilters := options.ArrayFilters{ |
| 40 | + Filters: []interface{}{ |
| 41 | + bson.M{"i.groups": bson.M{"$type": "array"}}, |
| 42 | + bson.M{"g.fields": bson.M{"$type": "array"}}, |
| 43 | + bson.M{ |
| 44 | + "f.field": "tile_type", |
| 45 | + "f.value": bson.M{ |
| 46 | + "$in": bson.A{"esri_world_topo", "stamen_watercolor", "stamen_toner"}, |
| 47 | + }, |
| 48 | + }, |
| 49 | + }, |
| 50 | + } |
| 51 | + opts := options.Update().SetArrayFilters(arrayFilters) |
| 52 | + |
| 53 | + updateCtx, cancel2 := context.WithTimeout(ctx, 30*time.Minute) |
| 54 | + defer cancel2() |
| 55 | + |
| 56 | + res, err := col.UpdateMany(updateCtx, filter, update, opts) |
| 57 | + if err != nil { |
| 58 | + return fmt.Errorf("update failed: %w", err) |
| 59 | + } |
| 60 | + |
| 61 | + fmt.Printf("[migration] matched: %d, modified: %d\n", res.MatchedCount, res.ModifiedCount) |
| 62 | + fmt.Printf("[migration] Migration completed. Updated %d documents.\n", res.ModifiedCount) |
| 63 | + return nil |
| 64 | +} |
0 commit comments