【问题标题】:MongoDb update if exists?MongoDb 更新是否存在?
【发布时间】:2022-11-26 06:17:40
【问题描述】:

我正在尝试逻辑( insert if not exists , but if exists update the records )

我是 MongoDB 的新手,但我曾经使用 mysql 来做到这一点,是否可以使用 mongoDB 来实现这一点?

到目前为止,这是我的代码,它在 ( insert if not exists ) 的情况下运行良好,但在 ( update if exists ) 的情况下运行良好

$db = new MongoDB\Client($conn);
    $collection = $db->auth->users;
        
        $collection->createIndex(
            array( "username" => 1 ),
            array( "unique" => true )
        );
        
    $document = array(
        "title" => "Mraaxs",
        "fullname" => "John C12344",
        "username" => "user1",
        "age" => 22
    );
    
    $collection->updateOne(
        array("username" => $document["username"]),
        array('$setOnInsert' => $document),
        array("upsert" => true)
    );

【问题讨论】:

  • 当前代码有什么问题?它会导致错误、文档重复、没有更改还是其他原因?

标签: php mongodb


【解决方案1】:

您很可能只需要将$setOnInsert 更改为$set

根据 documentation$setOnInsert 的说法:

如果更新操作没有导致插入,$setOnInsert 什么都不做。

所以它的行为与你描述的完全一样。 $setOnInsert 适用于“如果不存在则插入”并且对“如果存在则更新”不执行任何操作。

$set 将始终更新/将数据放入文档中。

这是文档中针对您的案例的 good example,同时使用 $set$setOnInsert

db.products.updateOne(
  { _id: 1 },
  {
     $set: { item: "apple" },
     $setOnInsert: { defaultQty: 100 }
  },
  { upsert: true }
)

When the upsert parameter is true db.collection.updateOne()
 - creates a new document
 - applies the $set operation
 - applies the $setOnInsert operation

The products collection contains the newly-inserted document:

{ "_id" : 1, "item" : "apple", "defaultQty" : 100 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 2021-01-04
    • 1970-01-01
    相关资源
    最近更新 更多