You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将MongoDB Shell查询转换为MongoDB Kotlin Driver代码

MongoDB Kotlin Driver 聚合查询转换实现

原始MongoDB Shell聚合查询

[
  {
    $match: {
      "attempts.badgeStatus": {
        $in: [
          "FILES_DOWNLOADED",
          "SAVED_TO_GCP_INCOMPLETE",
        ],
      },
    },
  },
  {
    $project: {
      tmsTenantId: 1,
      gptwClientId: 1,
      attempts: {
        $filter: {
          input: "$attempts",
          cond: {
            $in: [
              "$$this.badgeStatus",
              [
                "FILES_DOWNLOADED",
                "SAVED_TO_GCP_INCOMPLETE",
              ],
            ],
          },
        },
      },
    },
  },
]

对应的MongoDB Kotlin Driver代码

import org.litote.kmongo.*
import org.bson.conversions.Bson
import com.mongodb.client.model.Aggregates
import com.mongodb.client.model.Projections

// 假设枚举类定义如下
enum class BadgeAttemptStatus {
    FILES_DOWNLOADED,
    SAVED_TO_GCP_INCOMPLETE
}

// 构建聚合管道
val aggregationPipeline: List<Bson> = listOf(
    // 对应$match阶段
    Aggregates.match(
        Filters.`in`(
            (Badge::attempts / BadgeReplacementAttempt::badgeStatus).path(),
            listOf(
                BadgeAttemptStatus.FILES_DOWNLOADED.name,
                BadgeAttemptStatus.SAVED_TO_GCP_INCOMPLETE.name
            )
        )
    ),
    // 对应$project阶段
    Aggregates.project(
        Projections.fields(
            Projections.include(Badge::tmsTenantId.path()),
            Projections.include(Badge::gptwClientId.path()),
            // 使用computed实现$filter逻辑
            Projections.computed(
                Badge::attempts.path(),
                Expression.filter(
                    input = Expression.field(Badge::attempts.path()),
                    condition = Expression.`in`(
                        Expression.field("$$this." + BadgeReplacementAttempt::badgeStatus.path()),
                        listOf(
                            BadgeAttemptStatus.FILES_DOWNLOADED.name,
                            BadgeAttemptStatus.SAVED_TO_GCP_INCOMPLETE.name
                        )
                    )
                )
            )
        )
    )
)

// 执行聚合查询示例
val collection = mongoDatabase.getCollection<Badge>("badges")
val result = collection.aggregate<Badge>(aggregationPipeline).toList()

代码说明

  • $match阶段:通过Filters.in匹配attempts.badgeStatus属于指定状态列表的文档,使用属性引用路径避免硬编码字段名出错。
  • $project阶段:
    • 用Projections.include保留需要的tmsTenantId和gptwClientId字段;
    • 用Projections.computed结合Expression.filter实现Shell查询中的$filter逻辑,筛选出attempts数组内badgeStatus符合条件的元素。

内容的提问来源于stack exchange,提问作者Raydel Leyva Blanco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 18:05:22