简体   繁体   English

如何使用 MongoDB Scala 驱动程序在聚合投影内创建 $filter 运算符

[英]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.我知道有这个新的$filter运算符,但我不知道如何将它与 Scala 的 MongoDB 驱动程序一起使用。如果有人能提供帮助,我将不胜感激。

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. 这是在使用filter (字段i > 0)和project (将i10乘以后将输入转换为ITimes10值)流水线阶段之后进行aggregation方法。

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 有关更多详细信息,请访问此github链接mongo-scala-quick-tourmongo-scala-aggregation

I have an array locations and I want to keep in array object with field location where location string ends with "Deutschland"我有一个数组locations ,我想在数组 object 中保留字段location ,其中location字符串以“Deutschland”结尾

In shell it look:在 shell 中,它看起来是:

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

in Scala:在 Scala 中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM