I want to connect to mongo db using scala 3 and zio

I have a Scala 3 app using zio and zio-kafka.
The app also needs to connect to mongo db but I cant find any library which will let to do that.

the official scala driver for mongo is only for scala 2.12

I found mongo4cats but I don’t know how to convert a cats.effect.IO[A] to ZIO[R,E,A] using interop.

This is my sample mongo insert method

package com.example.testApp

import cats.effect.*
import com.mongodb.client.result.InsertOneResult
import mongo4cats.client.MongoClient
import mongo4cats.bson.Document

object DbOperationCats {
  def insert: IO[Unit] = 
    val client = MongoClient.fromConnectionString[cats.effect.IO](
    client.use { c =>
      for {
        _ <- IO.println("Starting session...")
        session <- c.startSession
        d <- c.getDatabase("sample-db")
        col <- d.getCollection("sample-collection")
        a <- col.insertOne(session, Document("name" -> "bilal"))
        _ <- IO.println("inserted")
      } yield ()

That’s not true, seems just documentation is not up-to-date: https://mvnrepository.com/artifact/org.mongodb.scala/mongo-scala-driver_2.13/4.3.3

For Scala 3, you should be able to use it thusly:

libraryDependencies += ("org.mongodb.scala" %% "mongo-scala-driver" % "4.3.3").cross(CrossVersion.for3Use2_13)

See Scala 3 in sbt 1.5 | The Scala Programming Language

Ohh wow thank you so much

While the mongo4cats example is written in terms of IO, in a quick glance at the code it looks like it is written in terms of the effect-neutral F[_] (as most good cats libraries are), so odds are decent that you could just plug in ZIO instead and have it largely work.

1 Like