【问题标题】:How to write redact aggregation in java?如何在java中编写编校聚合?
【发布时间】:2017-07-10 12:17:05
【问题描述】:

我正在尝试使用 Java 驱动程序使用聚合框架转换 MongoDb 查询。我被帮助在这里创建查询How to apply filter for output of aggregation framework of Mongo Db?

这里是示例聚合查询:

db.movies.aggregate(
[{
    $redact: {
        $cond: {
            if: {$gt: [{ $avg: "$customerReviews"}, 7 ] },
            then: "$$KEEP",
            else: "$$PRUNE"
        }
    }
},
{$skip:1},
{$limit:2}
]
);

我开始:

BasicDBObject avgQuery = new BasicDBObject("$avg", "$customerReviews");

但无法弄清楚如何执行 {$gt: [{ $avg: "$customerReviews"}, 7 ] }。我认为它应该类似于 gtQuery.put(avgQuery, new BasicDbObject("$gt",7)) 但显然不能在 put() 函数中放入 String 以外的东西。

顺便说一句,我不确定 $redact 是否只能使用 BasicDbObject 来完成,或者我需要像 Mongo spring query where two fields are equal 这样使用 Spring Mongo 的东西。希望有人可以帮助我完成整个查询。

【问题讨论】:

    标签: mongodb aggregation-framework mongo-java-driver


    【解决方案1】:

    BasicDBObject 是旧的 2.x mongo 版本类。使用较新的 3.x api 类。

    我在 java 驱动程序中没有看到任何帮助类来创建 redact 管道。

    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("dbname");
    MongoCollection<Document> collection = database.getCollection("dbcollection");
    List<Document> results = collection.aggregate(Arrays.asList(
                new Document("$redact", new Document("$cond",
                        Arrays.asList(new Document("$gt",
                        Arrays.asList(new Document("$avg", "$customerReviews"), 7)), 
                        "$$KEEP", "$$PRUNE"))),
                Aggregates.skip(1),
                Aggregates.limit(2)
    )).into(new ArrayList<>());
    

    你也可以使用

    String redact = "{\n" +
                "    $redact: {\n" +
                "        $cond: {\n" +
                "            if: {$gt: [{ $avg: \"$customerReviews\"}, 7 ] },\n" +
                "            then: \"$$KEEP\",\n" +
                "            else: \"$$PRUNE\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
    
    List<Document> results = collection.aggregate(Arrays.asList(
                Document.parse(redact),
                Aggregates.skip(1),
                Aggregates.limit(2)
    )).into(new ArrayList<>());
    

    【讨论】:

      猜你喜欢
      • 2012-04-09
      • 2019-08-19
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多