Mongodb:我应该使用 `foreach` 还是 `$lookup` 来使用来自 `collection2` 的数据对 `collection1` 执行更新以获得更好的性能?

Mongodb: should I use a `foreach` or a `$lookup` to perform an update on `collection1` using data from `collection2` for better performance?

我有两个集合,collection1collection2,我需要更新 collection1 中的所有记录,方法是用 collection2 中的一些相应数据装饰它们。对于 "join" 这些集合,我在两个集合中都有一个条目 userid,我可以使用它来识别匹配记录。

为了获得更好的性能,我应该使用 foreach 还是 $lookup

因此,当您使用 .find() 然后写回数据库时,您正在从数据库中读取一组数据并使用 foreach 遍历所有这些文档然后写回数据库再一次,如果你有一个庞大的数据集要处理,那么这绝对是一件耗时的事情,而且对应用程序和数据库服务器都有不必要的影响,这也可能很耗时,因为数据必须流经服务器,而不是这样。以防万一你必须得到这个路由检查 .bulkWrite() - 至少可以帮助你在一个数据库调用中编写文档,但有一个限制,它只能处理 100K 如果你发送更多的文档,那么它会在内部做块和处理数据——但我还没有用数百万的文档真正测试它。

随着您的版本 4.2.3,开始 MongoDB v4.2 聚合具有新功能 $merge that can help merge results of aggregation query to another collection, To be in safe point first try to write data to a new collection & if everything looks good write it on collection1 - at any point have a backup on collection1. This could save you sometime & also all the processing do happen in server side (Database side). Apart from this both approaches has read & write mechanism so test your queries are covered with indexes by using explain. Also consider aggregation-limits