【问题标题】:Call a Mongo function from aggregation pipeline through JAVA Driver API通过 JAVA Driver API 从聚合管道调用 Mongo 函数
【发布时间】:2022-01-06 08:40:09
【问题描述】:

我可以在 mongosh 中完成以下工作

var pipeline = [
    { $group: { _id: "$column1", valArray: { $push: "$column2" } } },
    { $set: {
            val: function1("$valArray", 70)    
        }
    },
    { $unset: [ "valArray" ] },
    { $sort: { _id: 1 } }
];

function1 是定义为以数组和数字为参数的函数

当我尝试使用 Java 进行相同操作时,我在尝试创建列表时遇到错误

List<Bson> pipeline = Stream.of(new String[] {
    "{ $group: { _id: \"$column1\", valArray: { $push: \"$column2\" } } }",
    "{ $set: { percentile_n: function1(\"$valArray\", " + percentileN + ") } }",
    "{ $unset: [ \"valArray\" ] }",
    "{ $sort: { _id: 1 } }"
  })
  .map(s -> Document.parse(s).toBsonDocument())
  .collect(Collectors.toList());


Exception in thread "main" org.bson.json.JsonParseException: **JSON reader was expecting a value but found 'function1'**.
    at org.bson.json.JsonReader.readBsonType(JsonReader.java:263)
    at org.bson.codecs.DocumentCodec.decode(DocumentCodec.java:175)
    at org.bson.codecs.DocumentCodec.decode(DocumentCodec.java:44)
    at org.bson.internal.LazyCodec.decode(LazyCodec.java:48)
    at org.bson.codecs.ContainerCodecHelper.readValue(ContainerCodecHelper.java:61)
    at org.bson.codecs.DocumentCodec.decode(DocumentCodec.java:177)
    at org.bson.codecs.DocumentCodec.decode(DocumentCodec.java:44)
    at org.bson.Document.parse(Document.java:126)
    at org.bson.Document.parse(Document.java:111)

看起来有一种特定的方法可以为函数调用创建 BsonDocument。有人可以帮忙吗?

【问题讨论】:

    标签: mongodb function


    【解决方案1】:

    似乎 Mongo 不利于从 API 在服务器上执行功能。只有通过 mongo shell 才允许这样做。

    【讨论】:

    • 这里API指的是与MongoDB Java Driver交互的方式。您的答案适用于通过 REST API 进行交互。
    【解决方案2】:

    我建议你使用 $function。您可以在the documentation 中找到一些参考资料。

    我刚刚在一个示例数据集上尝试了以下操作,它可以工作。

    db.getCollection('projects').aggregate([ 
      { $group: { _id: "$status", count: { $count: {} }, packages: { $push: "$packageSlip" } } }, 
      { $set: { val: { $function: { 
          body: function(currentDaysLeft, extraDays){ return currentDaysLeft + extraDays}, 
          args: ['$daysLeft', 70], 
          lang: "js" } } } }
    ])
    

    祝你好运

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 2023-03-26
      • 2020-09-05
      • 2016-04-26
      • 2021-01-29
      相关资源
      最近更新 更多