使用 Kotlin 在 MongoDB 中聚合构建器 :: 简单 addField 的表达式无法识别

问题描述 投票:0回答:1

我正在使用 mongodb kotlin-sync:4.11.0 驱动程序并连接到 4.4 版本的数据库。 在我的指南针内置聚合管道中,我有一个简单的 $addField 步骤,如下所示:

{
  newField: {
    $filter: {
      input: "$existingField",
      as: "ent",
      cond: {
        $eq: ["$$ent.primary", true],
      },
    },
  },
}

当它找到“existingField”的数组成员(其“primary”字段存在并设置为 True)时,它会正确添加新的数组字段。

Kotlin 中通过构建器的相同聚合阶段不是——我似乎无法获得正确的格式? MongoDB kotlin Docs 上的文档根本没有帮助。

看看下面,我在这里错过了什么?

fun onlyArrayMemberPrimaryValuesTrue(): Bson = Aggregates.set(
    Field("newField", Filters.elemMatch("existingField",
        Filters.eq("primary", true))
    )
)

简单的版本可以正常工作,任何更复杂的表达式的尝试都会失败。

val basic: Bson = set(Field("some.new.field", "\$some.existing.field"))     // ✅

mongodb kotlin aggregation-framework
1个回答
0
投票

不是 Kotlin 开发人员。您应该需要

Document
。文档中显示的演示提供了如何使用嵌套文档、附加多个字段和值数组。

Aggregates.set(
    Document("newField", 
        Document("$filter", 
            Document("input", "\$existingField")
                .append("as", "ent")
                .append("cond", 
                    Document("\$eq", listof("\$\$ent.primary", true))
                )
        )
    )
)
© www.soinside.com 2019 - 2024. All rights reserved.