检查 MongoDB upsert 是否进行了插入或更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13955212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:58:24  来源:igfitidea点击:

Check if MongoDB upsert did an insert or an update

mongodb

提问by

I can't find this in the documentation in any of the obvious places. I'd like to know if it is possible to know if Mongo executed an insert or update in the upsert operation?

我在文档中任何明显的地方都找不到这个。我想知道是否可以知道 Mongo 是否在 upsert 操作中执行了插入或更新?

采纳答案by Sammaye

Yes there is, on a safe call (or getLastError) the update function will return an array with an upsert field and a updatedExisting field.

是的,在安全调用(或 getLastError)中,更新函数将返回一个包含 upsert 字段和 updatedExisting 字段的数组。

You can read the PHP version of this here: http://php.net/manual/en/mongocollection.insert.phptowards the bottom.

你可以在这里阅读 PHP 版本:http: //php.net/manual/en/mongocollection.insert.php到底部。

As it says within the documentation on upserted:

正如它在文档中所说upserted

If an upsert occured, this field will contain the new record's _id field. For upserts, either this field or updatedExisting will be present (unless an error occurred).

如果发生了 upsert,该字段将包含新记录的 _id 字段。对于更新插入,将出现此字段或 updatedExisting(除非发生错误)。

So upserted contains the _idof the new record if a insert was done or it will increment updatedExistingif it updated a record.

因此_id,如果插入完成,则upserted 包含新记录的 ,或者updatedExisting如果它更新记录,它将增加。

I am sure a similar thing appears in all drivers.

我相信在所有驱动程序中都会出现类似的情况。

Edit

编辑

It will actually be a boolean in the updatedExistingfield of trueor false

它实际上是orupdatedExisting字段中的布尔值truefalse

回答by Sammaye

For reference only, in node.js:

仅供参考,在 node.js 中:

collection.update( source, target, { upsert: true }, function(err, result, upserted) {
  ...
});

回答by superiggy

For reference only, in node.js using Mongoose 3.6:

仅供参考,在 node.js 中使用 Mongoose 3.6:

model.update( findquery, updatequery, { upsert: true }, function(err, numberAffected, rawResponse) {
  ...
});

Where rawResponse looks like this when it has updated an existing document:

当 rawResponse 更新现有文档时,它看起来像这样:

{ updatedExisting: true,
  n: 1,
  connectionId: 222,
  err: null,
  ok: 1 }

And it looks like this when it has created a new document:

当它创建一个新文档时,它看起来像这样:

{ updatedExisting: false,
  upserted: 51eebc080eb3e2208a630d8e,
  n: 1,
  connectionId: 222,
  err: null,

(Both cases would return numberAffected = 1)

(两种情况都会返回 numberAffected = 1)

回答by Assem-Hafez

The Answer was taken from "MongoDB Applied Design Patterns" Book !determine whether an upsert was an insert or an update

答案取自“MongoDB 应用设计模式”一书!确定 upsert 是插入还是更新