name: portada class: portada-slide, center, middle # Mongo Driver ### Persistència en mongoDB .footnote[Mateu Yábar Valles] --- --- # Mongo Atlas Bases de dades MongoDB al núvol. --- # Driver Mongo - Driver offical Java - POJOCodec - treball amb classes i no documents --- # Gradle ``` implementation("org.mongodb:mongodb-driver-sync:4.7.1") ``` --- # Model ``` data class Item( var _id: ObjectId = ObjectId.get(), var complete: Boolean = false, var summary: String = "", var owner_id: String = "") ``` - Tot i no sér correcte en Kotlin deixarem els atributs _id i owner_id, per simplificar la configuració de Realm Sync --- # Definir client ``` val pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build() val pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider)) val connectionString = ConnectionString("mongodb+srv://$user:$password@cluster0.ojxu5mw.mongodb.net/?retryWrites=true&w=majority") val settings: MongoClientSettings = MongoClientSettings.builder() .applyConnectionString(connectionString) .serverApi( ServerApi.builder() .version(ServerApiVersion.V1) .build() ) .build() val mongoClient: MongoClient = MongoClients.create(settings) ``` --- # Col·lecció ``` val database: MongoDatabase = mongoClient.getDatabase("todo") .withCodecRegistry(pojoCodecRegistry); val collection: MongoCollection
= database.getCollection("Item", Item::class.java) ``` --- # Afegir ``` val item = Item(summary = "Something") collection.insertOne(item) ``` --- # Llistar ``` val items = collection.find().toList() val notCompleted = collection.find(Filters.eq("complete", false)) ``` --- # Creació Mongo Atlas - https://www.mongodb.com/cloud/atlas/register - Crea shared cluster (free) - a Cloud Provider & Region, selecciona'n un proper ## Security Quickstart - Crea un usuari i password per entrar - Add entries to your IP Access List: Afegeix la ip actual - Quan et surti "Introducing Termination Protection" fes skip Ja tens una instancia de MongoDb al núvol. T'hi pots connectar amb intellij ultimate usant la info a connect->Connect Using VS Code i copiant la info. --- # Documentació - https://www.mongodb.com/docs/drivers/java/sync/current/quick-start/ - https://learn.mongodb.com/learning-paths/mongodb-java-developer-path --- # Altres Per fer la suma de tots els elements, per cada un necessities fer un aggregate. Més info a :https://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/aggregation/ Exemples: ``` // Sum of all the fileds named num val sum = database.getCollection("LocationRealm").aggregate( listOf( Aggregates.group(null, Accumulators.sum("total", "\$num")) ) ).single()["total"] as Int? println(sum) ``` ``` // Sum of fileds named grouped by category val sumByCategoryResult = database.getCollection("LocationRealm").aggregate( listOf( Aggregates.group("\$category", Accumulators.sum("sum", "\$num")) ) ) sumByCategoryResult.forEach { println(it) } val sumByCategoryAsMap = sumByCategoryResult.map{Pair(it["_id"], it["sum"] as Int?)}.toMap() println(sumByCategoryAsMap) ```