mongo的insert和save比较

时间:2023-03-08 18:13:26
insert仅仅是插入文档到集合中,如果记录不存在则插入,如果记录存在则忽略
save是在文档不存在时插入,存在时则是更新

下面代码不是为了演示insert和save的:
    foreach ($menses['page'] as $k => $value) {
                if(isset($value['id'])) {
                    if(isset($value['is_del']) && intval($value['is_del']) === 1) {
                        //删除操作
                        $pull_date = array("menses.page"=> array("id" => $value['id']));
                        $this->update($where,$pull_date,true,'$pull');
                    } else {
                        //修改
                        $set_page['menses.page.$.color'] = isset($value['color'])?intval($value['color']):0;
                        $set_page['menses.page.$.time']  = strval($value['time']);
                        if(isset($value['image']) && !empty($value['image'])) {
                            if($value['image'] == '') {
                                $set_page['menses.page.$.image'] = '';
                            } else {
                                $set_page['menses.page.$.image'] = strval($value['image']);
                            }
                        } else {
                            $set_page['menses.page.$.image'] = '';
                        }
                        //$set_page['menses.page.$.image']   = isset($value['image'])?strval($value['image']):'';
                        $set_page['menses.page.$.status']  = isset($value['status'])?intval($value['status']):0;
                        $set_page['menses.page.$.timeline'] = time();
                        $where_aa = array("cuid"=>$cuid,"date"=>$menses['date'],"menses.page.id" => $value['id']);
                        $update = $set_page;
                        $this->update($where_aa,$update,true,'$set');
                    }
                } else {
                    //添加
                    $add_page['id']    = (string)new MongoId();
                    $add_page['color'] = intval($value['color']);
                    $add_page['time']  = strval($value['time']);
                    if(isset($value['image']) && !empty($value['image'])) {
                        if($value['image'] == '') {
                            $add_page['image'] = '';
                        } else {
                            $add_page['image'] = strval($value['image']);
                        }
                    } else {
                        $add_page['image'] = '';
                    }
                    //$add_page['image']   = isset($value['image'])?strval($value['image']):'';
                    $add_page['status']  = isset($value['status'])?intval($value['status']):0;
                    $add_page['timeline'] = time();
                    $update = array("menses.page"=>$add_page);
                    $this->update($where,$update,true,'$push',true);
                }
            }