【问题标题】:MongoDB: Insert a document if not exist, but skip updating in case it already existsMongoDB:如果不存在则插入文档,但如果它已经存在则跳过更新
【发布时间】:2021-06-03 22:52:46
【问题描述】:

如何在不存在的情况下在 mongoose 中插入文档而不更新现有文档(如果它已经存在)?我知道如果我执行 upsert,它会尝试更新(如果存在)并插入新文档(如果不存在)。但是,我的情况是我只想插入一个新文档(如果不存在)并保留现有文档而不更新它。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    你是在正确的方式。 您应该在update 方法中使用仍然使用upsert,但也应该使用$setOnInsert 运算符。请阅读此运算符here

    简而言之,使用此运算符允许您仅在导致插入新文档时执行操作。在其他情况下,它会简单地跳过。

    是的,你当然可以将它与猫鼬一起使用:

    YourModel.update(
      { queryField: 1 }, // query
      { $setOnInsert: { ...newDocument }}, // new doc fields
      { upsert: true } // still use upsert option
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-02
      • 2012-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多