Insert/query/update data from MongoDB + PHP + Web component

Now I will show you how to insert/ query/ update/ delete data from MongoDb with PHP and Web component.

Prepare

  1. Install mongodb on your server. Add a user with password. Build the connection string like "mongodb://username:password@yourHost:port". In my case, my connection string is like "mongodb://root:root@localhost:27017"
  2. Install php on server. Php version should be 7+.
  3. Install the mongodb driver for php. see here
  4. Upload the attached php file (see below ) to your server. Remember to change the connection string in the file.
  5. Goto http://your.site.domain/path/to/mongodb7.php. If you got {"error":"'collection' is missing"}, that means your prepare is successful.

Blocks

Snipaste_2022-10-27_19-41-17-1666871115887
Snipaste_2022-10-27_19-46-05
Snipaste_2022-10-27_20-17-03
Snipaste_2022-10-27_19-46-35

In the Web.GotText event, you will got a response.
The response text is a json string. you can parse it with Web.JsonTextDecodeWithDictionaries.

  1. if any error, there will be a key named "error";
  2. if no error, there will be a key named "count", means how many records qurered or effected.
  3. if action is "query", there is a key named "records", contains the records you wanted.

List of parameters

Please refer to here to find more, like how to write the filter, how to write the update newdata.

Testing url

For testing you may use this url (https://kevinkun.cn/other/mongodb7.php).
Remember to use a very very unique collection name (you may consider this as a password).

PHP file

<?php

/*
 * Writen by: Kevinkun
 * Date: 26/10/2022
 * Contact: wangsk789@qq.com
 */
 
//error_reporting(0);

$connectString = "mongodb://root:root@localhost:27017";//change this to your connectString

try{
    $manager = new MongoDB\Driver\Manager($connectString);  

    $result = [];
    
	
	// collection
	if(!isset($_REQUEST["collection"])){
		$result["error"]="'collection' is missing";
        die(json_encode($result));
	}
    $col = $_REQUEST["collection"];
    if(strpos($col,".")==false){
        $col = "db." . $col;
    }
    
	//action
    $action =strtolower(isset($_REQUEST["action"])?$_REQUEST["action"]:"");
    
    if ($action == "query") {
		//filter
        $filter = isset($_REQUEST["filter"])?$_REQUEST["filter"]:"{}";
        $filter = json_decode($filter);
        if(!$filter){
            $result["error"]="'filter' is not a well-formated json";
            die(json_encode($result));
        }
        $filter = (array)$filter;
		if(array_key_exists("_id", $filter)){
			$id = $filter["_id"];
			$filter["_id"] = new \MongoDB\BSON\ObjectId($id);
		}

		//sort
        $sort = array();    
        $order = isset($_REQUEST["sort"])?$_REQUEST["sort"]:"_id";
        $order = explode(",",$order);
        foreach($order as $k){
            if(substr($k,0,1)=="-"){
                 $sort[substr($k,1)] = -1;
            }else if(substr($k,0,1)=="+"){
                 $sort[substr($k,1)] = 1;
            }else{
                 $sort[$k] = 1;
            }
        }

		//keys
        $projection = array("_id"=>0);
        $keys = isset($_REQUEST["key"])?$_REQUEST["key"]:"-_id";
        $keys = explode(",",$keys);
        foreach($keys as $k){
            if(substr($k,0,1)=="-"){
             $projection[substr($k,1)] = 0;
            }else if(substr($k,0,1)=="+"){
                 $projection[substr($k,1)] = 1;
            }else{
                 $projection[$k] = 1;
            }
        }
		
        //limit and skip
        $limit = isset($_REQUEST["limit"])?$_REQUEST["limit"]:"0";
        $skip = isset($_REQUEST["skip"])?$_REQUEST["skip"]:"0";
    
        
        $options = [
            'projection' => $projection,
            'sort' => $sort,
            'limit' => $limit,
            'skip' => $skip,
        ];
    
        $query = new MongoDB\Driver\Query($filter, $options);
        $cursor = $manager->executeQuery("$col", $query);
        $records = $cursor->toArray();
        
        $result["records"] =  $records;
        $result["count"] = count($records);
        $result["action"]= "query";
        echo json_encode($result);
        
    }else if ($action == "insert") {
        $bulk = new MongoDB\Driver\BulkWrite;
        $body = isset($_REQUEST["document"])?$_REQUEST["document"]:"[]";
		if(strpos($body, "[") !== 0){
			$body = "[".$body."]";
		}
        $body = json_decode($body);
        if(!$body){
            $result["error"]="'document' is not a well-formated jsonArray";
            die(json_encode($result));
        }
        foreach ($body as $b){
            if(is_object($b)){
                $bulk->insert($b);
            }
        }

        $postresult = $manager->executeBulkWrite("$col", $bulk);
        $result["count"]= $postresult->getInsertedCount();
        $result["action"]= "insert";
        echo json_encode($result);
		
    }else if ($action == "delete") {
		//filter
        $filter = isset($_REQUEST["filter"])?$_REQUEST["filter"]:"";
	    $filter = json_decode($filter);
        if(!$filter){
            $result["error"]="'filter' is not a well-formated json";
            die(json_encode($result));
        }
        $filter = (array)$filter;
		if(array_key_exists("_id", $filter)){
			$id = $filter["_id"];
			$filter["_id"] = new \MongoDB\BSON\ObjectId($id);
		}

		$bulk = new MongoDB\Driver\BulkWrite;
		$bulk->delete($filter, ['limit' => 0]); 
		$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
		$delresult = $manager->executeBulkWrite("$col", $bulk, $writeConcern);
		$result["count"]= $delresult->getDeletedCount();
		$result["action"]= "delete";
		echo json_encode($result);
        
    }else if ($action == "update") {
		//filter
        $filter = isset($_REQUEST["filter"])?$_REQUEST["filter"]:"";
		$filter = json_decode($filter);
        if(!$filter){
            $result["error"]="'filter' is not a well-formated json";
            die(json_encode($result));
        }
        $filter = (array)$filter;
		if(array_key_exists("_id", $filter)){
			$id = $filter["_id"];
			$filter["_id"] = new \MongoDB\BSON\ObjectId($id);
		}
		
		//newobj
		$newobj = isset($_REQUEST["newobj"])?$_REQUEST["newobj"]:"[]";
		$newobj = json_decode($newobj);
		if(!$newobj){
				$result["error"]="'newobj' is not a well-formated json";
				die(json_encode($result));
		}
		
		$upsert = isset($_REQUEST["upsert"])?$_REQUEST["upsert"]:"";
		$upsert = strtolower($upsert)=="true"?true:false;

		$bulk = new MongoDB\Driver\BulkWrite;
		$bulk->update($filter, $newobj, ['multi'=>true, 'upsert'=>$upsert]);
		$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
		$updateresult = $manager->executeBulkWrite("$col", $bulk, $writeConcern);
		$result["count"]= $updateresult->getModifiedCount() + $updateresult->getUpsertedCount();
		$result["action"]= "update";
		echo json_encode($result);

        
    }else{
		$result["error"]="'action' is not recoginzed";
		die(json_encode($result));
    }
    
}catch (MongoDB\Driver\Exception\Exception $e) {
    $result["error"]= $e->getMessage();
    die(json_encode($result));
}
?>
5 Likes