如何将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
相关产品推荐
相关产品推荐

