在MongoDB中更新整个文档(所有字段)的最快方法是什么? [英] What is the fastest way to update the whole document (all fields) in MongoDB?

查看:596
本文介绍了在MongoDB中更新整个文档(所有字段)的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要更新整个文档并覆盖所有字段,但_id除外.就资源消耗而言,三种方法中哪一种是最好的:

Let's say I want to update the whole document and override all fields, except _id. What of the three methods is the best in terms of resource consumption:

1.将完整的文档设置为更新参数,以便传递所有字段

示例:

collection.update({_id: docId}, {$set:updateDoc});

2.计算原始文档和updateDoc之间的增量文档

示例:

const originalDoc = collection.findOne(docId);
const deltaDoc = calculateDeltaFct(originalDoc, updateDoc); //get changed fields
collection.update({_id: docId}, {$set:deltaDoc});

3.使用 Mongo 3.2. replaceOne函数

3. Use the Mongo 3.2. replaceOne function

示例:

collection.replaceOne({_id: docId}, {$set:updateDoc});

我对每种方法的优缺点都有一个假设,但我想确定选择什么以及为什么选择.我不确定如何精确测量它,所以也许有人可以帮忙.

I have an assumption of the pros and the cons of each methods but I want to be sure what to choose and why. I am not sure how to measure it precisely, so maybe someone can help.

背景:

我有一个度量标准集合,其中许多文档经常更新,但是要更新的字段变化很大,因此很难为每个字段编写更新方法.相反,我打算只放入所有数据并更新所有字段,因此我仅使用一种用于所有更新的更新方法来保持代码整洁.

I have a metrics collection where many documents are updated often, but the fields to be updated vary a lot, so it is hard to write an update method for each field. Instead I intend to just throw all data in and update all fields, so I keep my code clean with only one update method for all updates.

更新:

在我的设置中,文档结构中没有嵌入任何子文档.我的(dev)设置中也没有分片和复制功能.

In my setup, there are no subdocuments embedded in the document structure. I also have no sharding and replication in my (dev) setup.

此外,我找到了一些方法( collection.explain ),我也会用它来研究该主题.不过,非常感谢您的帮助或提示.

Furthermore I found some method (collection.explain) which I will use to research on that topic, too. Nevertheless, any help or hint is much appreciated.

推荐答案

这实际上取决于您在更新之前是否需要旧信息.如果您要覆盖信息,甚至覆盖一个键->值对,那么我将使用updatereplaceOne.差异可能在时间上有所不同,具体取决于集合(数据集)的大小.如果这是值得关注的基准差异.就我个人而言,我倾向于replaceOne,但这只是基于经验和我处理过的馆藏.

It really depends if you require the old information before the update. If you are overwriting the info and even for one key - > value pair then I would use either update or replaceOne. The difference may be in time depending on the size of your collection (dataset). If that is of concern benchmark the difference. Personally I would lean towards replaceOne, but that is just based on experience and the collections I deal with.

对于您所解释的内容,我认为您的第二个选择要么不是高效的,要么是精通内存的.听起来好像不需要这样的计算就可以简单地更新数据,而无需担心覆盖先前的信息.

For what you have explained I don't think your second choice is either efficient or being memory savvy. It does not sound like you need such a calculation for simply updating data where there is no concern over overwriting previous information.

这篇关于在MongoDB中更新整个文档(所有字段)的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆