'How to make $filter operator inside a projection of an aggregation using the MongoDB Scala Driver

I need to filter array of embedded documents inside a projection of an aggregation operation. I know there is this new $filter operator, but I do not know how to use it with the MongoDB driver for Scala. If anyone can help, I appreciate it.



Solution 1:[1]

I have an array locations and I want to keep in array object with field location where location string ends with "Deutschland"

In shell it look:

db.someCollection.aggregate([{
    $project: {
        locations: {
            $filter: {
                input: "$locations",
                as: "item",
                cond: {
                    "$regexMatch": {
                        "input": "$$item.location",
                        "regex": "Deutschland$"
                    }
                }
            }
        }
    }
}])

in Scala:

collection("someCollection").
      aggregate[TypeOfObjectInArray](Seq(
    project(fields(
      computed("locations", Document ("$filter" ->
        Document("input" -> "$locations", "cond" ->
          Document("$regexMatch" -> Document("input" -> "$$this.location", "regex" -> "Deutschland$")))))
      )
    )
  )
)

Solution 2:[2]

Here is way to do aggregation after using filter(field i > 0) and project (convert input as ITimes10 value after multiplying i with 10) pipeline stages.

import org.mongodb.scala.model.Aggregates._

collection.aggregate(Seq(filter(gt("i", 0)),
  project(Document("""{ITimes10: {$multiply: ["$i", 10]}}""")))
).printResults()

For more details visit this github links mongo-scala-quick-tour and mongo-scala-aggregation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roman Kazanovskyi
Solution 2 Puneeth Reddy V