Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void main(String[] args) {
- System.out.println("Dataset cleanup migration");
- // set your MongoDB Cluster connection string
- // TODO> Ticket: Migration - set the cluster connection string.
- String mongoUri = "mongodb+srv://m220student:m220password@mflix-cpo7t.mongodb.net/test?retryWrites=true";
- // instantiate database and collection objects
- MongoDatabase mflix = MongoClients.create(mongoUri).getDatabase("mflix");
- MongoCollection<Document> movies = mflix.getCollection("movies");
- Bson dateStringFilter = type("lastupdated", "string");
- String datePattern = "yyyy-MM-dd HH:mm:ss";
- // TODO> Ticket: Migration - create a query filter that finds all
- // documents that are required to be updated and the correct date
- // format pattern
- Bson queryFilter = new Document("lastupdated",new Document("$type",BsonType.STRING));
- SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
- // create list of bulkWrites to be applied.
- List<WriteModel<Document>> bulkWrites = new ArrayList<>();
- // iterate over the documents and apply the transformations.
- for (Document doc : movies.find(dateStringFilter)) {
- // Apply lastupdate string to date conversion
- WriteModel<Document> updateDate = transformDates(doc, dateFormat);
- if (updateDate != null) {
- bulkWrites.add(updateDate);
- }
- }
- // TODO> Ticket: Migration - create a query filter that finds
- // documents where `imdb.rating` is of type string
- Bson ratingStringFilter = type("imdb.rating", "string");
- for (Document doc : movies.find(ratingStringFilter)) {
- // Apply "imdb.rating" string to number conversion
- WriteModel<Document> updateRating = transformRating(doc);
- if (updateRating != null) {
- bulkWrites.add(updateRating);
- }
- }
- // execute the bulk update
- // TODO> Ticket: Migration - set the bulkWrite options
- BulkWriteOptions bulkWriteOptions = new BulkWriteOptions().ordered(false);
- if (bulkWrites.isEmpty()) {
- System.out.println("Nothing to update!");
- System.exit(0);
- }
- BulkWriteResult bulkResult = movies.bulkWrite(bulkWrites, bulkWriteOptions);
- // output the number of updated documents
- System.out.println(
- MessageFormat.format("Updated {0} documents", bulkResult.getModifiedCount()));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement