首页 > 解决方案 > 持久化聚合结果

问题描述

我们尝试在返回之前将集合操作的结果保存到单独的集合中。

  Aggregates.project(
                                Projections.fields(
                                Projections.computed("diff", 
                                        Document.parse("{ $setDifference: [{\"local\", \"$global\"] }"))
                                ,Projections.excludeId()
                                )
                        )
                        ,Aggregates.unwind("$diff",new UnwindOptions().preserveNullAndEmptyArrays(true))
                        ,Aggregates.out("globaldata")

但是,这似乎取代了全局数据集合,而不是附加到它。
Mongo 3.6 中是否有出路($merge 仅适用于 4.2.x)

标签: mongodbmongodb-queryaggregation-framework

解决方案


还没有@IUnknown,但在探索后发现其中一位 MongoDB 开发人员在这里写道,他们已经为$out

IE;

$out: {
    mode: "replaceCollection" | "replaceDocuments" | "insertDocuments",
    to: "targetCollection",
    uniqueKey: {<set of fields that uniquely identify the document>},
}

但是在阅读了 MongoDB 的官方文档后,我找不到 $out 的任何新更新。但是,您将看到新的$merge管道,它提供了与在此处附加文档相同的功能。

在 MongoDB 4.2 中

{ $merge: {
     into: <collection> -or- { db: <db>, coll: <collection> },
     on: <identifier field> -or- [ <identifier field1>, ...],  // Optional
     let: <variables>,                                         // Optional
     whenMatched: <replace|keepExisting|merge|fail|pipeline>,  // Optional
     whenNotMatched: <insert|discard|fail>                     // Optional
} }

因此,您最好更新您的 MongoDB 版本。


推荐阅读