Giter Site home page Giter Site logo

cronometro's Introduction

Hi there 馃憢

import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoCollection; import com.mongodb.client.AggregateIterable; import com.mongodb.client.model.*; import org.bson.Document;

import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;

import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date;

public class MongoBulkWriteByPeriod { public static void main(String[] args) { // Conexi贸n a MongoDB MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase database = mongoClient.getDatabase("tu_base_de_datos"); MongoCollection collection = database.getCollection("tu_coleccion");

    // Aqu铆 comienza el pipeline de agregaci贸n
    List<Document> pipeline = new ArrayList<>();
    pipeline.add(new Document("$group", new Document("_id", "$_id")
            .append("fecha", new Document("$first", "$fecha_operacion"))  // Extraemos la fecha
            .append("totalEntradas", new Document("$sum", "$entradas"))));

    // Ejecutar el pipeline de agregaci贸n
    AggregateIterable<Document> result = collection.aggregate(pipeline);

    // Map para guardar listas de operaciones bulk por cada colecci贸n (por periodo)
    Map<String, List<WriteModel<Document>>> bulkOperationsByCollection = new HashMap<>();

    // Iterar sobre los resultados de la agregaci贸n
    for (Document doc : result) {
        // Extraer la fecha de la operaci贸n (ISODate)
        Date fechaOperacion = doc.getDate("fecha");

        // Convertir la fecha en un LocalDateTime para extraer a帽o y mes
        LocalDateTime localDate = fechaOperacion.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        int year = localDate.getYear();
        int month = localDate.getMonthValue();

        // Crear el nombre de la colecci贸n basada en el periodo (a帽o y mes en formato YYYYMM)
        String collectionName = String.format("%d%02d", year, month);  // Genera el nombre, por ejemplo "202406"

        // Filtrar por el _id (para la operaci贸n de reemplazo o actualizaci贸n)
        Document filter = new Document("_id", doc.get("_id"));

        // Crear operaci贸n ReplaceOneModel con upsert para actualizar o insertar el documento
        ReplaceOneModel<Document> replaceOne = new ReplaceOneModel<>(
                filter,
                doc,
                new ReplaceOptions().upsert(true)
        );

        // Si la colecci贸n (por periodo) no est谩 en el mapa, inicializar la lista de operaciones para ella
        bulkOperationsByCollection.putIfAbsent(collectionName, new ArrayList<>());

        // A帽adir la operaci贸n a la lista de la colecci贸n correspondiente
        bulkOperationsByCollection.get(collectionName).add(replaceOne);
    }

    // Iterar sobre las colecciones y ejecutar las operaciones bulkWrite por cada una
    for (Map.Entry<String, List<WriteModel<Document>>> entry : bulkOperationsByCollection.entrySet()) {
        String collectionName = entry.getKey();
        List<WriteModel<Document>> bulkOperations = entry.getValue();

        // Obtener la colecci贸n por nombre
        MongoCollection<Document> targetCollection = database.getCollection(collectionName);

        // Ejecutar el bulkWrite en la colecci贸n correspondiente
        if (!bulkOperations.isEmpty()) {
            BulkWriteResult bulkWriteResult = targetCollection.bulkWrite(bulkOperations);

            // Mostrar los resultados del bulkWrite
            System.out.println("Colecci贸n: " + collectionName);
            System.out.println("Inserted: " + bulkWriteResult.getInsertedCount());
            System.out.println("Modified: " + bulkWriteResult.getModifiedCount());
            System.out.println("Matched: " + bulkWriteResult.getMatchedCount());
            System.out.println("Upserts: " + bulkWriteResult.getUpserts());
        }
    }

    // Cerrar la conexi贸n al cliente
    mongoClient.close();
}

}

cronometro's People

Contributors

izuharus avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    馃枛 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 馃搳馃搱馃帀

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google 鉂わ笍 Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.