$out 在聚合 MongoDB 中

Mil*_*aci 5 java mongodb nosql-aggregation

谁能解释一下为什么在 Java 中,当我使用“$out”进行聚合管道时,当我只写以下内容时,不会将结果写入新集合中:

     Document match = new Document("$match", new Document("top_speed",new  Document("$gte",350)));
     Document out=new Document("$out", "new_collection");
            coll.aggregate(Arrays.asList(
            match,out
            )
            );
Run Code Online (Sandbox Code Playgroud)

当我保存聚合结果并对其进行迭代时,会创建新集合并且匹配的结果在里面(在这种情况下,Java 显然有错误):

    AggregateIterable<Document> resultAgg=
            coll.aggregate(Arrays.asList(
            match,out
            )
            );

    for (Document doc : resultAgg){

            System.out.println("The result of aggregation match:-"+    doc.toJson());
    }
Run Code Online (Sandbox Code Playgroud)

我不明白为什么。

小智 1

您可以调用toCollection()方法而不是迭代。

Document match = new Document("$match", new Document("top_speed", new Document("$gte", 350)));
Document out = new Document("$out", "new_collection");
coll.aggregate(Arrays.asList(match, out)).toCollection();
Run Code Online (Sandbox Code Playgroud)