检查MongoDB upsert是否插入或更新

57 mongodb

我在任何一个显而易见的地方的文档中都找不到这个.我想知道是否有可能知道Mongo是否在upsert操作中执行了插入或更新?

Sam*_*aye 35

是的,在安全调用(或getLastError)上,update函数将返回一个带有upsert字段和updatedExisting字段的数组.

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

正如它在文档中所述upserted:

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

因此_id,如果插入已完成,则upserted包含新记录,如果updatedExisting 更新了记录,则会增加.

我相信所有司机都会出现类似的情况.

编辑

它实际上是或者updatedExisting字段中的布尔值truefalse


小智 11

仅供参考,在node.js中:

collection.update( source, target, { upsert: true }, function(err, result, upserted) {
  ...
});
Run Code Online (Sandbox Code Playgroud)

  • 名称来源和目标有点误导IMO. (2认同)

sup*_*ggy 10

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

model.update( findquery, updatequery, { upsert: true }, function(err, numberAffected, rawResponse) {
  ...
});
Run Code Online (Sandbox Code Playgroud)

当rawResponse更新现有文档时,其中的内容如下所示:

{ updatedExisting: true,
  n: 1,
  connectionId: 222,
  err: null,
  ok: 1 }
Run Code Online (Sandbox Code Playgroud)

它在创建新文档时看起来像这样:

{ updatedExisting: false,
  upserted: 51eebc080eb3e2208a630d8e,
  n: 1,
  connectionId: 222,
  err: null,
Run Code Online (Sandbox Code Playgroud)

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


Ass*_*fez 6

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