Note
The following page discusses on-demand materialized views.下一页讨论按需物化视图。For discussion of views, see Views instead.有关视图的讨论,请参见视图。
Starting in version 4.2, MongoDB adds the 从4.2版开始,MongoDB为聚合管道添加了$merge stage for the aggregation pipeline.$merge阶段。This stage can merge the pipeline results to an existing collection instead of completely replacing the collection.此阶段可以将管道结果合并到现有集合,而不是完全替换集合。This functionality allows users to create on-demand materialized views, where the content of the output collection can be updated each time the pipeline is run.此功能允许用户创建按需物化视图,每次运行管道时都可以更新输出集合的内容。
Assume near the end of January 2019, the collection 假设在2019年1月底,bakesales contains the sales information by items:bakesales集合包含按项目列出的销售信息:
The following 下面的updateMonthlySales function defines a monthlybakesales materialized view that contains the cumulative monthly sales information.updateMonthlySales函数定义了一个monthlybakesales物化视图,该视图包含累计的每月销售信息。In the example, the function takes a date parameter to only update monthly sales information starting from a particular date.在本例中,函数采用日期参数,仅更新从特定日期开始的每月销售信息。
$match stage filters the data to process only those sales greater than or equal to the startDate.$match阶段过滤数据以仅处理大于或等于startDate的销售。$group stage groups the sales information by the year-month.$group阶段按年度和月份对销售信息进行分组。$merge stage writes the output to the monthlybakesales collection.$merge阶段将输出写入monthlybakesales集合。
Based on the 根据_id field (the default for unsharded output collections), the stage checks if the document in the aggregation results matches an existing document in the collection:_id字段(非分片输出集合的默认值),该阶段检查聚合结果中的文档是否与集合中的现有文档匹配:
For the initial run, you can pass in a date of 对于初次运行,您可以传递一个日期new ISODate("1970-01-01"):new ISODate("1970-01-01"):
After the initial run, the 在初次运行之后,monthlybakesales contains the following documents; i.e. db.monthlybakesales.find().sort( { _id: 1 } ) returns the following:monthlybakesales包含以下文档;即,db.monthlybakesales.find().sort({ _id: 1 })返回以下内容:
Assume that by the first week in February 2019, the 假设到2019年2月的第一周,bakesales collection is updated with newer sales information; specifically, additional January and February sales.bakesales集合更新了较新的销售信息;具体来说,是1月和2月的额外销售。
To refresh the 要刷新一月和二月的monthlybakesales data for January and February, run the function again to rerun the aggregation pipeline, starting with new ISODate("2019-01-01").monthlybakesales数据,请再次运行该函数以重新运行聚合管道,从new ISODate("2019-01-01")开始。
The content of monthlybakesales has been updated to reflect the most recent data in the bakesales collection; i.e. db.monthlybakesales.find().sort( { _id: 1 } ) returns the following:monthlybakesales的内容已更新,以反映bakesales集合中的最新数据;即,db.monthlybakesales.find.sort( { _id: 1 } )返回以下内容:
See 有关以下内容,请参阅$merge for:$merge以了解:
$merge and available options$merge的更多信息和可用的选项。