note 129840 added to mongodb.tutorial.library

From: Date: Thu, 07 Nov 2024 09:21:18 +0000
Subject: note 129840 added to mongodb.tutorial.library
Groups: php.notes 
Request: Send a blank email to php-notes+get-221635@lists.php.net to get a copy of this message
One question that was unanswered was how to handle insertion of a full JSON document provided as an argument (or in a string variable). The mongodb extension can handle this by simply using json_decode() to convert the JSON document to an object that can then be easily inserted, e.g. (with full document provided as the 2nd command-line argument) <?php /* include libmongo API */ require "vendor/autoload.php"; /* include connection string, db and collection values */ require __DIR__ . '/site/db-mongo-inc.php'; /* use MongoDBClient; */ use MongoDB\Client; /* connection string */ $uri = "mongodb://$user:$pass@localhost"; /* attempt connection to database with $uri */ $client = new MongoDB\Client("$uri"); if (!isset($client)) { echo 'error: connection failed'; } /* define collection of documents */ $collection = $client->$db->$collection; /* insert JSON document from string variable (here $argv[2]) */ if ($argc > 2) { $jsobj = json_decode ($argv[2]); if ($jsobj) { $iresult = $collection->insertOne ( $jsobj ); if (!$iresult) { printf ("error: insert of object failed.\n"); } } } ?> The extension's block insert feature recursively resolves all field and data values contained in the object and inserts the entire document in the collection. It is helpful to remove the "_id:" field and have that auto-generated for you to avoid issues. ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.84.18 (proxied: 66.76.46.195) ---- Manual Page -- https://php.net/manual/en/mongodb.tutorial.library.php Edit -- https://main.php.net/note/edit/129840 Del: integrated -- https://main.php.net/note/delete/129840/integrated Del: useless -- https://main.php.net/note/delete/129840/useless Del: bad code -- https://main.php.net/note/delete/129840/bad+code Del: spam -- https://main.php.net/note/delete/129840/spam Del: non-english -- https://main.php.net/note/delete/129840/non-english Del: in docs -- https://main.php.net/note/delete/129840/in+docs Del: other reasons-- https://main.php.net/note/delete/129840 Reject -- https://main.php.net/note/reject/129840 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221635) next »