【问题标题】:mongo insert record if exist or update the record in mongo using phpmongodb插入记录(如果存在)或使用php更新mongodb中的记录
【发布时间】:2017-02-24 15:29:55
【问题描述】:

我是 mongodb 的新手,我正在尝试编写一个 cron 文件,该文件将从我的 mysql 中获取记录并将其存储在 mongo 集合中。现在我想要的是我需要编写另一个代码来检查 mongo 集合是否有该记录。如果没有则意味着它必须插入或更新记录

我的代码是这样的。

 $query="select * from tt";
 $result=mysqli_query($connect,$query);
 while($fetch=mysqli_fetch_array($result)){
 $uname=$fetch['name'];
 $lastname=$fetch['lastname'];
 $surname=$fetch['surname'];
 $age=$fetch['age'];

$document=array("name"=>$uname,"lastname"=>$lastname,"surname"=>$surname,"age"=>$age);

我想在这里检查记录是否在mongo中

$update = $collection->update($criteria,$document,array( 'upsert' =>true));

我不知道在 -criteria 中给出什么

【问题讨论】:

    标签: php mongodb


    【解决方案1】:

    您应该只使用 $document 作为标准:

    $collection->update($document, $document, ['upsert' => true]);
    

    但是,如果某个特定字段存在唯一索引,则您可以使用该字段进行查询。

    【讨论】:

    • 是的,我试过了,但它再次插入了一条新记录。它没有更新任何东西......
    猜你喜欢
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2016-01-13
    • 2018-11-30
    • 2021-11-13
    • 1970-01-01
    相关资源
    最近更新 更多